#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;
/*
4.2 对象的初始化和清理
4.2.3 拷贝构造函数调用时机
三种情况下会调用:
使用一个已创建完毕的对象来初始化一个新对象
以值传递的方式给函数参数传值
以值方式返回局部对象
*/
class Person{
public:
Person(){
cout << "Person 无参默认构造函数" << endl;
}
Person(int _age){
cout << "Person 有参构造函数" << endl;
age = _age;
}
Person(const Person & p){
cout << "Person 拷贝构造函数" << endl;
age = p.age;
}
~Person(){
cout << "Person 析构函数" << endl;
}
int age;
};
// 1 使用一个已创建完毕的对象来初始化一个新对象
void test1(){
Person p1(20);
Person p2(p1);
cout << "p2的年龄:" << p2.age << endl;
}
// 2 以值传递的方式给函数参数传值
void dowork(Person p){}
void test2(){
Person p;
dowork(p);
}
// 3 以值方式返回局部对象
Person dowork2(){
Person p1;
cout << (int *)&p1 << endl;
return p1;
}
void test3(){
Person p = dowork2();
cout << (int *)&p << endl;
}
int main(){
//test1();
/*
Person 有参构造函数
Person 拷贝构造函数
p2的年龄:20
Person 析构函数
Person 析构函数
*/
//test2();
/*
Person 无参默认构造函数
Person 拷贝构造函数
Person 析构函数
Person 析构函数
*/
//test3();
// bug解决参考https://blog.csdn.net/baidu_41692782/article/details/105845198
/*
Person 无参默认构造函数
0x6dfe4c
Person 拷贝构造函数
Person 析构函数
Person 拷贝构造函数
Person 析构函数
0x6dfec8
Person 析构函数
*/
system("pause");
return 0;
}
11.2.3重学C++之【拷贝构造函数调用时机】
猜你喜欢
转载自blog.csdn.net/HAIFEI666/article/details/114842136
今日推荐
周排行