#include<iostream>usingnamespace std;//c++拷贝构造函数调用时机分三种//1、使用一个已经创建完毕的对象初始化一个新对象//2、值传递的方式给函数参数传值//3、以值方式返回局部对象classPerson{public://构造函数Person(){
cout <<"默认构造函数的调用"<< endl;}Person(int a){
age = a;
cout <<"有参构造函数调用"<< endl;}//拷贝构造函数Person(const Person &p){
age = p.age;
cout <<"拷贝构造函数调用"<< endl;}//析构函数~Person(){
cout <<"析构函数的调用"<< endl;}int age;};//1、使用一个已经创建完毕的对象初始化一个新对象voidtest01(){
Person p1(10);
Person p2(p1);
cout << p1.age << endl;
cout << p2.age << endl;}//2、值传递的方式给函数参数传值voiddoWork(Person p){}voidtest02(){
Person p;doWork(p);}//3、值方式返回局部对象
Person doWork2(){
Person p1;return p1;}voidtest03(){
Person p =doWork2();}intmain(){//test01();//test02();test03();system("pause");return0;}
3、构造函数的调用规则
#include<iostream>usingnamespace std;//构造函数的调用规则//1、创建一个类 C++编译器会给每个类都添加至少3个函数//默认构造 (空实现)//析构函数 (空实现)//拷贝构造 (值拷贝)//2、如果我们写了有参构造函数 编译器就不再提供默认构造 依然提供拷贝构造//3、如果我们写了拷贝构造,前面两个就不提供classPerson{public://构造函数/*Person()
{
cout << "默认构造函数的调用" << endl;
}*/Person(int a){
age = a;
cout <<"有参构造函数调用"<< endl;}//拷贝构造函数//Person(const Person &p)//不写也可以打印 编译器默认提供//{// age = p.age;// cout << "拷贝构造函数调用" << endl;//}//析构函数~Person(){
cout <<"析构函数的调用"<< endl;}int age;};//1、使用一个已经创建完毕的对象初始化一个新对象//void test01()//{// //Person p;// p.age = 18;// Person p2(p);// cout << p2.age << endl;//}voidtest02(){//Person p;
Person p(20);
Person p2(p);}intmain(){//test01();test02();system("pause");return0;}
4、深拷贝和浅拷贝
#include<iostream>usingnamespace std;classPerson{public://构造函数Person(){
cout <<"默认构造函数的调用"<< endl;}Person(int a,int b){
age = a;
height =newint(b);
cout <<"有参构造函数调用"<< endl;}Person(const Person &p){
cout <<"拷贝构造函数调用"<< endl;
age = p.age;//height = p.height;//编译器默认实现这行代码,有误,需要自己进行深拷贝操作//深拷贝操作
height =newint(*p.height);}//析构函数~Person(){//析构代码 将堆区开辟数据做释放操作if(height !=NULL){delete height;
height =NULL;}
cout <<"析构函数的调用"<< endl;}int age;int*height;};voidtest01(){
Person p(18,160);
Person p2(p);
cout << p.age <<*p.height<< endl;
cout << p2.age <<*p2.height<< endl;}intmain(){test01();system("pause");return0;}