Juan Manuel
Juan Manuel

Reputation: 51

'<<' & '>>' operators overloading

I've been writing a complex numbers header from scratch for a school class but I'm stuck on the extraction and insertion operators overload, I've been reading a lot about that topic but I still don't get it

friend ostream& operator << (ostream &tmp, Cmplx &param)
{
    tmp<<param.Re<<"+"<<param.Im<<"i";
    return tmp;
}
friend istream& operator >> (istream &tmp, Cmplx &param)
{
    tmp>>param.Re;
    tmp>>param.Im;
    return tmp;
}

But when I try to compile I get.

no match for 'operator<<' in 'std::cout << Cmplx<vartype>::operator+(Cmplx<vartype>) [with vartype = long double](Cmplx<long double>(((const Cmplx<long double>&)((const Cmplx<long double>*)(& B)))))'

Thanks in advance

EDIT: The Implementation:

#include"cmplx oper.hpp"
using namespace std;

int main()
{
Cmplx<long double> A, B;
cin >> A;
cin >> B;
cout<<(A+B)<<(A-B)<<(A*B)<<(A/B)<<(A+B).norm<<(A+B).pol<<(A+B).conj<<(A+B).re<<(A+B).im<<endl;
getch();
return true;
}

Also the modification, I changed the parameter to const:

friend ostream& operator << (ostream &tmp, Cmplx const &param)
{
    tmp<<param.Re<<"+"<<param.Im<<"i";
    return tmp;
}

Still not working

EDIT 2: I broke down the cout line and found that the problem was a pair of methods in my class, not actually the use of the '+' operator. I still don't know why but at least I could compile.

Also, I wonder if I can get an specific style input for my class, I mean something like

scanf("%d+%di",Re,Im);

But using cin (I cannot, or at least I don't know how to use scanf since It's a template, and it's pretty awkward to write an specific cin for each type of data)

EDIT 3: I found the problem, a lack of parenthesis.

Upvotes: 1

Views: 417

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

You didn't show your use of it, but in this case I can see what's up.

You're doing something like std::cout << (Cmplx1 + Cmplx2);.

The result of (Cmplx1 + Cmplx2) is a temporary; temporary expressions may not be bound to references.

For example:

int f() {
   return 3;
}

int& x = f(); // ill-formed

However, as a special piece of C++ magic, temporaries can be bound to references-to-const:

For example:

int f() {
   return 3;
}

int const& x = f(); // magic!

The temporary then lives as long as the reference-to-const does.

If your operators take references to const complex objects, then you can bind a temporary as the second parameter:

friend ostream& operator<<(ostream& os, Cmplx const& param)
{
    os << param.Re << "+" << param.Im << "i";
    return os;
}

Conveniently, you ought to have done this in the first place as you will not be modifying param (and, in an operator<<, never should).

Hope that helps.

Upvotes: 5

Related Questions