当我初始化我的类的对象时,默认和复制构造函数都被调用。C++构造函数调用顺序
class A
{
public:
A (string s) { str = string (s); cout << "default" << endl; }
A (int n) { cout << "A (int n)" << endl; }
A (string s, int n) { cout << "A (string s, int n)" << endl; }
A (int n2, string s2) { cout << "A (int n2, string s2)" << endl; }
A (const A& a) { str = a.str; cout << "copy" << endl; }
inline void printA() { cout << str << endl; }
string str;
};
int main (void)
{
A a_1 = A ("con 1");
cout << endl;
A a_2 = "con 2";
cout << endl;
A a_3 = A (4);
A a_4 = A ("a_4", 10);
cout << endl;
A a_5 = A (11, "a_5");
cout << endl;
cin.get();
return 0;
}
结果:
default copy default A (int n) A (string s, int n) copy A (int n2, string s2) copy
为什么a_1
,a_3
和a_4
调用默认和复制两个构造? A_3也有一个参数,但它不需要拷贝构造函数。
为什么要添加一个默认构造函数? – curiousguy
@curiousguy:我想在这里更清楚地描述问题。我可以这样做:'A(){cout <<“default”<< endl; }并将当前的默认构造函数改为:A(string s){str = string(s);} cout <<“A(string s)”<< endl; }'得到更好的调试信息。此外,如果您将'Foo()'设为私有,则此构造函数在类之外变为不可用。然后,有'显式'关键字,做我不记得:) AFAIK就是这样。 –
@MartinBerger请在你的问题中编辑“_Why是A_1 calling default_”。 – curiousguy