繁体   English   中英

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

[英]Is there a way to modify 'operator->' so that 'z->im' returns imaginary part of complex number

我有一个对复数建模的结构 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 ->的重载必须要么返回一个原始指针,要么返回一个 object(按引用或按值),而operator ->又被重载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM