有没有办法修改'operator->',以便'z->im'返回复数的虚部



我有一个结构Cmplx,它对复数进行建模。

class Cmplx{
double x;
double y;
public:
Cmplx(int X, int Y){x = X; y = Y;}
double& operator->(...){...}
}

我需要实现运算符,以便

int main(){
Cmlpx z(1,2);
z->im = 5;
z->re = 2;
}

将我的复数更改为 (2,5(;当 im 和 re 是字符串时,我知道该怎么做,但不知道如何这样做。

你可能会这样滥用operator->

struct ComplexRef
{
ComplexRef* operator->() { return this;}
double& re;
double& im;
};
class Cmplx{
double x;
double y;
public:
Cmplx(int X, int Y){x = X; y = Y;}
ComplexRef operator->(){ return {x, y}; }
};

演示

operator ->的重载必须返回原始指针,或者返回operator ->反过来重载的对象(通过引用或值(。

最新更新