当前位置: 代码迷 >> 综合 >> operator=重载
  详细解决方案

operator=重载

热度:55   发布时间:2023-11-23 22:56:57.0
//operator=必须是成员函数
class Person {
    
public:Person(int age);
public:Person();Person& operator=(const Person& p1);//类内成员函数重载“=”~Person();int *age;
};Person::Person(int age) {
    this->age = new int(age);
}
Person::~Person() {
    if (age != NULL) {
    delete age;age = NULL;}
}Person::Person() {
    this->age = new int(18);//默认18
}Person& Person::operator=(const Person& p1) {
    //调用时this->operator=(p1)可简化为this=p1;/*if (this->age != NULL) {delete this->age;this->age = NULL;}this->age = new int(*p1.age);*/*this->age = *p1.age;//类自带operator=函数但是为浅拷贝,对于在堆区创建的数据需要深拷贝,需要对operator重写return *this;
}void test() {
    Person person(18);Person p2(19);Person p3;cout << *p3.age << endl;p3= person=p2;cout << *p3.age << endl;cout << *person.age << endl;
}int main() {
    test();
}
  相关解决方案