类和对象Ⅶ----拷贝构造函数

拷贝构造函数:用对象初始化对象

#include<iostream>

using namespace std;

class Point {
	
	int x, y;
	
	public:
		
		//带两个参数的构造函数 
		Point (int a, int b) {
			
			x = a;
			y = b;
			cout<<"Constructing"<<endl; 
		}
		
		//拷贝构造函数
		Point(const Point &p) {
			
			x = p.x;
			y = p.y;
			cout<<"Copy Constructing"<<endl; 
		} 
		
		//析构函数 
		~Point () {
			
			cout<<"Constructing"<<endl;
		} 
		
		void show() {
			
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
};

//Point temp = p2;
//该函数一共调用3次拷贝构造函数 
//该语句会调用拷贝构造函数 
Point fun (Point temp) {
	
	//该语句也会调用拷贝构造函数 
	Point p(temp);
	
	//创建临时对象,没有名字的对象
	//用p创建对象 
	return p;
} 

int main () {
	
	//创建对象p1调用构造函数 
	Point p1(1, 1);
	Point p2(2, 2);
	
	//调用两次拷贝构造函数 
	//用已存在的对象p1来创建对象p3 
	Point p3(p1);
	//用已存在的对象p2来创建初始化对象p4
	Point p4 = p2;
	
	//该语句不会调用拷贝构造函数 
	//会调用等号运算符 
	//p4 = p1;
	//p4 = fun(p2);
	
	return 0;
}

执行结果:

 

 后4个Constructing分别是由p4,p3,p2,p1引起的

#include<iostream>

using namespace std;

class Point {
	
	int x, y;
	
	public:
		
		//带两个参数的构造函数 
		Point (int a, int b) {
			
			x = a;
			y = b;
			cout<<"Constructing"<<endl; 
		}
		
		//拷贝构造函数
		Point(const Point &p) {
			
			x = p.x;
			y = p.y;
			cout<<"Copy Constructing"<<endl; 
		} 
		
		//析构函数 
		~Point () {
			
			cout<<"Destructing"<<endl;
		} 
		
		void show() {
			
			cout<<"("<<x<<","<<y<<")"<<endl;
		}
};

//Point temp = p2;
//该函数一共调用3次拷贝构造函数 
//该语句会调用拷贝构造函数 
Point fun (Point temp) {
	
	//该语句也会调用拷贝构造函数 
	Point p(temp);
	
	//创建临时对象,没有名字的对象
	//用p创建对象 
	return p;
} 

int main () {
	
	//创建对象p1调用构造函数 
	Point p1(1, 1);
	Point p2(2, 2);
	
	//调用两次拷贝构造函数 
	//用已存在的对象p1来创建对象p3 
	Point p3(p1);
	//用已存在的对象p2来创建初始化对象p4
	Point p4 = p2;
	
	//该语句不会调用拷贝构造函数 
	//会调用等号运算符 
	p4 = p1;
	p4 = fun(p2);
	
	return 0;
}

此代码的执行结果:

注:这个结果有误,目前没有发现代码问题〒▽〒。。。

正确的执行结果应该是这样

 

第三个 Copy Constructing 是Point fun (Point temp) {}引起的

第四个 Copy Constructing 是Point p(temp);引起的

第五个 Copy Constructing 是return p引起的

释放空间,调用析构函数

第一个Destructing是return p引起的

第二个Destructing是Point p(temp);引起的

第三个Destructing是Point fun (Point temp) {}引起的

第四个Destructing是P4引起的

第五个Destructing是P3引起的

第六个Destructing是P2引起的

第七个Destructing是P1引起的

(即与构造的顺序完全相反)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值