拷贝构造函数的定义

1.拷贝构造函数的定义:

复制构造函数参数为类对象本身的引用,用于根据一个已经存在的对象复制出一个新的该类的对象,一般在函数中会将已经存在对象的数据成员的值复制一份到新的对象中,如果没有写拷贝构造函数,则系统会默认创建一个复制构造函数,当类中有指针成员时,由系统默认创建该构造函数会存在风险。

Stu.h

#ifndef STU_H_
#define STU_H_


class Stu
{
public:
	int age;
	int no;
	Stu();
	~Stu();


	Stu(Stu &r);
};


#endif /* STU_H_ */
Stu.cpp
 
#include "Stu.h"
#include <iostream>
using namespace std;
Stu::Stu()
{
	cout<<"Stu()"<<endl;
}


Stu::~Stu()
{
	cout<<"~Stu()"<<endl;
}


//复制构造函数
Stu::Stu(Stu &r) {
	cout<<"Stu::Stu(Stu &r)"<<endl;
	this->age = r.age;  //此处的this指向当前正在创建的对象stu2,所以 Stu &r=stu1,r指的是stu2,把stu1的值赋给stu2,调用了拷贝构造函数,如果用户没有定义,则系统默认调用系统的拷贝构造函数。
	this->no = r.no;
}

main.cpp
#include <iostream>
using namespace std;
#include "Stu.h"
#include "Test.h"
void f1() {
	Stu stu1;
	stu1.age = 100;
	stu1.no = 100;


	Stu stu2(stu1);//调用复制构造函数
	cout<<stu2.age<<endl;//100
	cout<<stu2.no<<endl;//100
}
//void f2() {
//	Test t1;//   t1:  *p
//	t1.p = (int *)malloc(sizeof(int));
//	Test t2(t1);//t2: *p
//}
void f3() {
	Test t1( (int *) malloc(sizeof(int)) );
	Test t2( (int *) malloc(sizeof(int)) );
	Test t3( (int *) malloc(sizeof(int)) );


	Test t4(t3);
}
int main() {
	f3();
	return 0;
}
















  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值