于构造函数的调用次数,这里有个小总结:
简单粗暴
测试代码:
#include <iostream>
using namespace std;
class Test{
int a;
public:
Test(){
a = 0;
cout << "Default Constructor" << endl;
}
Test(Test &t){
cout << "Copy Constructor" << endl;
a = t.a;
}
Test& Test :: operator = (const Test &t){
cout << "Assign Constructor" << endl;
if (&t == this)
return *this;
a = t.a;
return *this;
}
~Test(){
cout << "Deconstructor" << endl;
}
};
int main(){
cout << "Test *t = new Test;" << endl;
Test *t = new Test;
cout << "Test tt(*t);" << endl;
Test tt(*t);
cout << "Test ttt;" << endl;
Test ttt;
cout << "ttt = tt;" << endl;
ttt = tt;
cout << "Test tttt = tt;" << endl;
Test tttt = tt;
cout << "delete t;" << endl;
delete t;
cout << "Test a[4];" << endl;
Test a[4];
cout << "Test *p[4];" <<endl;
Test *p[4];
cout << "Over" << endl;
system("pause");
return 0;
}
运行结果:
注意:类声明指针的时候不调用构造函数。
补充一下思路:
A a[3] 这里会调用3次;
A b 这里调用1次;
最后new调用一次;
单独新建类指针和引用是不会调构造函数的
5次。a[3]这3次,b一次,r是b的引用,没有构造,p在new的时候一次,所以一共5次。