赋值运算符重载
约 42 个字 41 行代码 预计阅读时间 1 分钟
运算符重载的方法有友元或者成员函数两种途径,但是赋值运算符只能使用成员函数的方法来实现
#include <iostream>
using namespace std;
class Person{
public:
Person(int age){
this->age = new int (age);
}
Person& operator= (Person &p){
if (age != nullptr){
delete age;
age = nullptr;
}
age = new int (*p.age);
return *this;
}
~Person(){
if (age != nullptr){
delete age;
age = nullptr;
}
}
int * getAge(){
return this->age;
}
private:
int * age;
};
void test1(){
Person p1(15);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
cout << *p3.getAge() << endl;
}
int main(){
test1();
return 0;
}