C++Note 构造析构函数调用时机
C++中拷贝构造函数调用时机通常有三种情况
*使用一个已经创建完毕的对象来初始化一个新对象
*值传递的方式给函数参数传值
*以值方式返回局部对象
1 #include <iostream> 2 using namespace std; 3 4 5 class Person 6 { 7 public: 8 Person() 9 { 10 cout << "Person默认构造函数的调用" << endl; 11 } 12 Person(int age) 13 { 14 m_Age = age; 15 cout << "Person有参构造函数的调用" << endl; 16 } 17 Person(const Person& p) 18 { 19 cout << "Person拷贝构造函数的调用" << endl; 20 m_Age = p.m_Age; 21 } 22 ~Person() 23 { 24 cout << "Person析构函数的调用" << endl; 25 } 26 int m_Age; 27 }; 28 //拷贝构造函数调用时机 29 30 //1.使用一个已经创建完毕的对象来初始化一个新对象 31 void test01() 32 { 33 Person p1(20); 34 Person p2(p1); 35 cout << "p2的年龄为:" << p2.m_Age << endl; 36 } 37 38 //2.值传递的方式给函数参数传值 39 void doWork(Person p) 40 { 41 42 } 43 void test02() 44 { 45 Person p;//默认构造函数调用 46 doWork(p);//拷贝构造函数调用 47 } 48 49 //3.值方式返回局部对象 50 Person doWork2() 51 { 52 Person p1; 53 return p1; 54 } 55 void test03() 56 { 57 Person p = doWork2(); 58 } 59 int main() 60 { 61 //test01(); 62 //test02(); 63 test03(); 64 system("pause"); 65 return 0; 66 }
浙公网安备 33010602011771号