如何重载赋值运算符以满足 ob1=ob2=ob3(ob1,ob2,ob3 是同一类的对象)

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

本文关键字:ob2 ob3 ob1 一类 对象 何重载 赋值运算符 满足 重载      更新时间:2023-10-16

如何重载赋值运算符以满足 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&);

或者,更好的是,按值传递并使用复制和交换习惯

用法
A& operator=(A);

有关运算符重载的出色介绍,请参阅此处。