原因和解决方案
原因:C语言允许在定义变量时添加多余的括号,这使得在某些情况下当你想调用构造函数时,编译器无法分清你是在调用构造函数还是在定义变量(即int(a)
可被编译器理解为int a
)
解决方案:
- 使用强制类型转换
- 使用{}代替()调用构造函数 (C++11)
举例说明
#include <iostream>
using namespace std;
struct Dog
{
Dog(const string &name) { this->name = name; }
string name;
};
struct DogOwner
{
DogOwner(const Dog &dog) { this->dog = new Dog{dog}; }
Dog *dog;
};
int main()
{
string dogName = "momiji";
DogOwner aya(Dog(dogName)); //该行会报警
}
原因分析
由于C语言允许在定义变量时添加多余的括号,所以
DogOwner aya(Dog(dogName));
也可被编译器理解为:
DogOwner aya(Dog dogName);
编译器无法分清该行是要调用构造函数还是定义变量,从而导致出现 parentheses were disambiguated as a function declaration 警告
解决方案
1.使用强制类型转换
DogOwner aya((Dog)dogName);
2.使用{}调用构造函数
DogOwner aya(Dog{dogName});
参考链接:
[1]: https://zh.wikipedia.org/wiki/%E6%9C%80%E4%BB%A4%E4%BA%BA%E7%83%A6%E6%81%BC%E7%9A%84%E8%A7%A3%E6%9E%90 “最令人烦恼的解析”