#include <iostream> using namespace std; class Base { friend ostream& operator<<(ostream &os,Base &b); public: Base() { cout << "Base()" << endl; } ~Base() { cout << "~Base()" << endl; } Base(const Base &b) { cout << "Copy Base()" << endl; } Base& operator=(const Base &b) { cout << "Copy assignment" << endl; return *this; } }; int main() { Base b; cout << "---------------" << endl; Base b1 = b; //拷贝初始化,调用拷贝构造函数。(注意和下面的区别: //现在b已经初始化了,不用再调用相应的构造函数了) //注意:不是调用copy assignment operator // string s = "abc"; // ①先调用对应的构造函数构建一个临时对象temp("abc") // ②再调用copy constructor 初始化s。 cout << "---------------" << endl; Base b2(b); //拷贝初始化,调用拷贝构造函数 cout << "---------------" << endl; Base b3; cout << "---------------" << endl; b3 = b;//调用Copy assignment cout << "---------------" << endl; }
看看这题的输出结果:
#include <iostream> class human { public: human() { human_num++; } ; static int human_num; ~human() { human_num--; print(); } void print() { cout << "human num is: " << human_num << endl; } protected: private: }; int human::human_num = 0; human f1(human x) { x.print(); return x; } int main(int argc, char* argv[]) { human h1; h1.print(); human h2 = f1(h1); h2.print(); return 0; }
输出:human num is: 1
human num is: 1
human num is: 0
human num is: 0
human num is: -1
human num is: -2
----------------------------
分析:
1. human h1; //调用构造函数,hum_num++后为1 ;
h1.print(); 输出:"human is 1" 。
2. human h2 = f1(h1); //在调用函数 f1(h1)的过程中,由于函数参数是按值传递对象,调用
默认的复制构造函数(实参h1的副本h1_copy给形参x)
,它并没有对hum_num++,所以hum_num 仍= 1,所以x.print()输出:"human is 1" 。
3. 由于该函数 f1
返回一个human 对象(其实返回的是副本),所以又调用默复制认构造函数,创建一个返回值的副本 h1_return。
4. 在退出函数
f1 时,要销毁实参h1传递过来的副本对象h1_copy,调用析构函数(human_num--),输出:"human is 0"。
5. 把返回值的副本赋给h2,又调用默认构造函数( human_num = 0); h2.print(); //输出: human is 0;
6. 在退出main()函数的时候,先销毁h2,调用析构函数(human_num--),输出"human_num is -1"。
7. 然后销毁h1,调用析构函数(human_num--),输出"human_num is -2"。