Question

Consider the code

#include <stdio.h>

class complex
{
private:
    double re,im;
public:
    complex(double, double);
    complex(double);
    complex operator+(complex c);
    double getre();
    double getim();
};

complex complex::operator+(complex c)
{
    return *new complex(re+c.getre(),im+c.getim());
}

complex::complex(double real, double imagine)
{
    re= real;
    im= imagine;
}

complex::complex(double real)
{
    re= real;
    im=0;
}

double complex::getre()
{
    return re;
}

double complex::getim()
{
    return im;
}

int main()
{
    complex *z= new complex(2.0);
    complex *w= new complex(3.0, 4.0);
    printf("%f\n",(2.0+*z).getre());//Compile error: no match for ‘operator+’ in ‘2.0e+0 + * z’

}

But if we replaced our operator member function to a non-member function like the following:

complex operator+(complex t, complex c)
{
    return *new complex(t.getre()+c.getre(),t.getim()+c.getim());
}

then it works fine. But I'm expected that it will work in all descibed cases. We've defined constructor conversion as.

Was it helpful?

Solution

Binary operators don't attempt any conversion to the left side argument, the "receiver" of the function.
If you want a builtin type on the left hand side, the overload must be a free function.

The simplest way is usually to have a mutating member, += in this case, and delegate to that from the free function(s).

Something like this:

complex complex::operator+=(complex rhs)
{
    re += rhs.re;
    im += rhs.im;
    return *this;
}

complex operator+(complex t, complex c)
{
    t += c;
    return t;
}    

int main()
{
    complex z(2.0);
    complex w(3.0, 4.0);
    printf("%f\n",(2.0 + z).getre());
}

You should also make your getters const.

And you receive a gold star for not having setters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top