c++ 赋值运算符重载

#include<iostream>
using namespace std;
#include <string>
#include <ostream>
class person {
public:
	int* m_age;
	person(int age) {
		//将年龄数据开辟到堆区
		m_age = new int(age);
		//用m_age接收传来的age 为什么要用指针?
	}
	person& operator=(person &p) {//这里的意思是连续引用
		if (m_age!=NULL) {
			delete m_age;
			m_age = NULL;
		}

		//编译器提供的代码是浅拷贝
		//m_age=p.m_age;
		//我们修改提供深拷贝 解决浅拷贝的问题
		m_age = new int(*p.m_age);
		//传进来的是person类型的 所以有p.m_age
		//把定义的m_age开辟到堆区
		//返回自身
		return *this;
	}
	~person()
	{
		if (m_age!=NULL) {
			delete m_age;
			m_age = NULL;
		}
	}
};
void test01() 
{
	person p1(18);
	person p2(20);
	person p3(30);
	p3 = p2 = p1;
	cout << "p1的年龄为:" << *p1.m_age << endl;//用*是解引用
	cout << "p2的年龄为:" << *p2.m_age << endl;
	cout << "p3的年龄为:" << *p3.m_age << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}

c++编译器至少给一个类添加4个函数

1. 默认构造函数(无参,函数体为空)
2. 默认析构函数(无参,函数体为空)
3. 默认拷贝构造函数,对属性进行值拷贝
4. 赋值运算符 operator=, 对属性进行值拷贝
 

用Person接收重构的赋值运算符 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值