33,311
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
//赋值运算符重载
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
//参数必须是引用类型,若是值类型,在函数结束时会执行析构函数把指针(传入的p.m_Age)指向的内存空间释放掉.
Person& operator=(Person &p)
{
//如果有未释放的堆区空间,先释放
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
m_Age = new int(*p.m_Age);
return *this;
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
int *m_Age;
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
//对于自定义数据类型,等号运算符重载返回值必须是引用类型
//如上方代码相当于p3.operator=(p2.operator=(p1));,其中参数传递过程
即 Person &p = p2.operator=(p1);,如果operator= 函数返回的是值类型
//则会先在内存中创建一个临时对象temp用于接收传递来的对象副本,然后用这个临时对象为引用p初始化
//而临时对象生命周期很短,仅在当前语句结束后就释放其内存空间,而后再通过p访问临时变量的内存空间则是非法操作。
cout << "p1的年龄为:" << *p1.m_Age << endl;
cout << "p2的年龄为:" << *p2.m_Age << endl;
cout << "p3的年龄为:" << *p3.m_Age << endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
//赋值运算符重载
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
//重载赋值运算符,用深拷贝解决浅拷贝的问题
//在堆区开辟新的空间将被拷贝对象中指针成员所指向的值拷贝过来
//参数必须是引用类型,若是值类型,在函数结束时会执行析构函数把指针(传入的p.m_Age)指向的内存空间释放掉.
Person operator=(Person &p)
{
//判断是否自我赋值
if(&p == this)
{
return *this;
}
//如果有未释放的堆区空间,先释放
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
//深拷贝
m_Age = new int(*p.m_Age);
return *this;
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
int *m_Age;
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
//如上方代码相当于p3.operator=(p2.operator=(p1));,其中参数传递过程即 Person &p = p2.operator=(p1);,如果operator= 函数返回的是值
//则会先在内存中创建一个临时对象temp用于接收传递来的对象副本,然后用这个临时对象为引用p初始化
//而临时对象声明周期很短,仅在当前语句结束后就释放其内存空间,而后再通过p访问临时变量的内存空间则是非法操作。
cout << "p1的年龄为:" << *p1.m_Age << endl;
cout << "p2的年龄为:" << *p2.m_Age << endl;
cout << "p3的年龄为:" << *p3.m_Age << endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}