这是两个班级
class A
{
std::string s;
public:
A() { prn("A constructor"); }
A(std::string s) : s(s) { prn("A not empty constructor"); }
A(const A&) { prn("A copy constructor"); }
A& operator =(const A& a) { prn("A = operator"); return *this; }
void p() { prn("in A"); }
};
class B
{
public:
A a;
B(A aa) : a(aa) { prn("B constructor"); }
B() { prn("B default constructor"); }
};
Run Code Online (Sandbox Code Playgroud)
现在以下代码正常工作
B b(A("sa"));
b.a.p();
Run Code Online (Sandbox Code Playgroud)
打印:
一个不空的构造
拷贝构造函数
乙构造
的一个
但是如果我使用没有参数的A构造函数会发生奇怪的事情
B b(A());
Run Code Online (Sandbox Code Playgroud)
编译并运行但没有输出(没有调用构造函数)
B b(A());
b.a.p(); // error here
Run Code Online (Sandbox Code Playgroud)
得到编译错误.那么这两个构造函数之间的区别是什么?
B b(A());
Run Code Online (Sandbox Code Playgroud)
这不会声明对象.它声明了一个b带有返回类型的函数B,它接受一个返回类型A作为参数的函数的指针.
你想要的是:
B b = A();
Run Code Online (Sandbox Code Playgroud)
或者(谢谢Kerrek):
B b((A()));
Run Code Online (Sandbox Code Playgroud)
或者在C++ 11中:
B b {A()};
Run Code Online (Sandbox Code Playgroud)
这有时被称为烦恼的解析.