拷贝构造函数

1.自定义拷贝构造函数

#include<iostream>
#include<string>
#include<string.h>
using namespace std;
class Human
{
private:
    /* data */
    int age;
    std::string name;
public:
    Human(/* args */);
    ~Human();
    Human(const Human&);
    int get();
};

Human::Human(/* args */)
{
    age =10;
    name="hello";
}

Human::~Human()
{
}
 Human::Human(const Human& h)
 {
    this->age =h.age +1;
    this->name=h.name;
 }
int Human::get() {
    return this->age;
}

int main(){
    Human h;
    Human h2(h);
    std::cout << h2.get() << std::endl;

    return 0;
}

2.合成的拷贝构造函数

属于浅拷贝

#include<iostream>
#include<string>
#include<string.h>
using namespace std;
class Human
{
private:
	/* data */
	int age;
	std::string name;
	char* addr;
public:
	Human(/* args */);
	~Human();
	//Human(const Human&);//不定义拷贝构造函数,编译器会生成“合成的拷贝构造函数”
	int get();
};

Human::Human(/* args */)
{
	age = 14;
	name = "hello";
	addr = new char[64];
	strcpy_s(addr, 64, "China");
}

Human::~Human()
{
}
//  Human::Human(const Human& h)
//  {
//     this->age =h.age +1;
//     this->name=h.name;
//  }
int Human::get() {
	return this->age;
}

int main() {
	Human h;
	Human h2(h);
	std::cout << h2.get()<< std::endl;

	return 0;
}

说明:

合成的拷贝构造函数的缺点: 使用“浅拷贝

解决方案:在自定义的拷贝构造函数中,使用‘深拷贝

Human::Human(const Human &man) {
	cout << "调用自定义的拷贝构造函数" << endl;
	age = man.age;      //this是一个特殊的指针,指向这个对象本身
	salary = man.salary;
	name = man.name;
	// 深度拷贝
	addr = new char[64];
	strcpy_s(addr, 64, man.addr);
}

什么时候调用拷贝构造函数

  1. 调用函数时,实参是对象,形参不是引用类型

   如果函数的形参是引用类型,就不会调用拷贝构造函数

  1. 函数的返回类型是类,而且不是引用类型
  2. 对象数组的初始化列表中,使用对象。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值