如何重载赋值运算符以满足 ob1=ob2=ob3(ob1、ob2、ob3 是相同 class 的对象)

how to overload assignment operator to satisfy ob1=ob2=ob3 (ob1,ob2,ob3 are objects of same class)

如何重载赋值运算符以满足 ob1=ob2=ob3(ob1、ob2、ob3 是相同 class 的对象)我们不关心 (ob2 = ob3) 类似于 (ob2.operator=(ob3)) 但当我们将此结果分配给 ob1 时,我们需要类型为 class 的参数,类似于 (ob1.operator=(ob2.operator=(ob3) )下面是给我错误的代码

#include<bits/stdc++.h>
using namespace std;
class A
{
public:
    int x;
    int *ptr;
    A()
    {
    }
    A(int a, int *f)
    {
        x = a;
        ptr = f;
    }
    void operator=(A&);
};
void A::operator=(A &ob)
{
    this->x = ob.x;
    *(this->ptr) = *(ob.ptr);
}
int main()
{
    int *y = new int(3);
    A ob1, ob2, ob3(5, y);
    ob1 = ob2 = ob3;
    cout << ob1.x << " " << *(ob1.ptr) << endl;
    cout << ob2.x << " " << *(ob2.ptr) << endl;
    cout << ob3.x << " " << *(ob3.ptr) << endl;
    return 0;
}

您的赋值运算符应 return 对 *this 的引用,并定义为

A& operator=(const A&);

或者,更好的是,按值传递并使用 copy-and-swap idiom

A& operator=(A);

有关运算符重载的精彩介绍,see this