C++ //拷贝构造函数调用时机//1.使用一个已经创建完毕的对象来初始化一个新对象 //2.值传递的方式给函数参数传值 //3.值方式返回局部对象

 1 //拷贝构造函数调用时机
 2 
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 //1.使用一个已经创建完毕的对象来初始化一个新对象
 8 
 9 
10 //2.值传递的方式给函数参数传值
11 
12 
13 //3.值方式返回局部对象
14 
15 
16 class Person
17 {
18 public:
19     Person()
20     {
21         cout << "Person默认构造函数调用" << endl;
22     }
23     Person(int age)
24     {
25         cout << "Person有参构造函数调用" << endl;
26         m_Age = age;
27     }
28 
29     Person(const Person& p)
30     {
31         cout << "Person拷贝构造函数调用" << endl;
32         m_Age = p.m_Age;
33     }
34 
35     ~Person()
36     {
37         cout << "Person析构函数调用" << endl;
38     }
39 
40 
41     int m_Age;
42 };
43 
44 //1.使用一个已经创建完毕的对象来初始化一个新对象
45 void test01()
46 {
47     Person p1(20);
48     Person p2(p1);
49 
50     cout << "p2的年龄为:" << p1.m_Age << endl;
51 }
52 
53 //2.值传递的方式给函数参数传值
54 void doWork(Person p)
55 {
56 
57 }
58 void test02()
59 {
60     Person p;
61     
62     doWork(p);
63     
64 }
65 
66 
67 //3.值方式返回局部对象
68 Person doWork2()
69 {
70     Person p1;
71     cout << (int*)&p1 << endl;
72     return p1;
73 }
74 void test03()
75 {
76     Person p = doWork2();
77 
78     cout << (int*)&p << endl;
79 
80 }
81 int main()
82 {
83     //test01();
84     test02();
85     
86     test03();
87     system("pause");
88 }

 

posted on 2021-08-06 14:14  Bytezero!  阅读(65)  评论(0编辑  收藏  举报