如何重载赋值运算符以满足ob1 = ob2 = ob3(ob1,ob2,ob3是同一类的对象),而我们不关心(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;
}

最佳答案

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

A& operator=(const A&);

或者更好的是,按值传递并使用copy-and-swap idiom
A& operator=(A);

有关操作员重载的出色介绍,请see this

关于c++ - 如何重载赋值运算符以满足ob1 = ob2 = ob3(ob1,ob2,ob3是同一类的对象),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47208683/

10-11 16:53