C ++运算符 - >在复数的情况下

时间:2018-06-19 07:45:22

标签: c++ class operator-overloading complex-numbers

问题是实现具有两个双倍Cplx的{​​{1}}课,x代表复数的实部和虚部。
其中一个子任务是使用以下描述实现y

operator ->z­->re):访问z­->im的实部和虚部(您必须实现更改z)。

我遇到麻烦z->re = 5我从来没有真正理解它是如何运作的所以我的问题是:operator ->如何运作以及何时使用它以及如何在这个问题中应用这个想法。

2 个答案:

答案 0 :(得分:6)

以下是您所要求的......但不确定它是您想要的:

template <typename T>
struct ReIm
{
    const ReIm* operator ->() const { return this; }
    ReIm* operator ->() { return this; }

    T re;
    T im;
};


struct Cplx
{
    double x;
    double y;

    ReIm<double> operator ->() const { return {x, y}; }
    ReIm<double&> operator ->() { return {x, y}; }
};

Demo

答案 1 :(得分:1)

- &gt;运算符用于取消引用指向对象的指针,并在一个运算符中获取成员变量/函数。例如,

Cplx* cplxPointer = new Cplx();
cplxPointer->x = 5;

相同
Cplx* cplxPointer = new Cplx();
(*cplxPointer).x = 5;

它只是取消引用指针然后获取成员变量(或函数,如果你想要)。除非我误解了你的问题,否则上述内容应该可以帮助你完成作业。