1

The problem is to implement class Cplx with two doubles x and y represent real and imaginary part of complex numbers.
One of the subtask is to implement operator -> with following description:

(z­->re and z­->im): access to the real and imaginary part of z(You must implement changing like z->re = 5).

I have troubles with operator -> I never really understand how it works so my question is: how -> works and when to use it and how to apply that idea in this problem.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
josf
  • 3
  • 9
  • Wasn't the *pointer to member* operator covered in the lectures? – Bathsheba Jun 19 '18 at 07:48
  • If you really must name the doubles `x` and `y` implementing the behaviour `z->re` would be rather complicated. (Or I misunderstand the task description, it’s hard to follow, to be honest.) – idmean Jun 19 '18 at 07:49
  • @idmean: Not so complicated, but very strange. – Jarod42 Jun 19 '18 at 08:04
  • [Arrow operator (->) usage in C&C++](https://stackoverflow.com/questions/2575048/arrow-operator-usage-in-c) – Ehsan Panahi Jun 19 '18 at 08:43

2 Answers2

6

The following does what you ask... But not sure it is what you want:

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

The -> operator works to dereference a pointer to an object and get a member variable/function in one operator. For example,

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

Is the same as

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

It just dereferences the pointer and then gets the member variable (or function if you want). Unless I misunderstood your question, the above should be able to help you complete your assignment.

cepiolot
  • 71
  • 9