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 ¶m)
{
tmp<<param.Re<<"+"<<param.Im<<"i";
return tmp;
}
friend istream& operator >> (istream &tmp, Cmplx ¶m)
{
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 ¶m)
{
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.
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:
However, as a special piece of C++ magic, temporaries can be bound to
references-to-const:For example:
The temporary then lives as long as the
reference-to-constdoes.If your operators take references to
constcomplex objects, then you can bind a temporary as the second parameter:Conveniently, you ought to have done this in the first place as you will not be modifying
param(and, in anoperator<<, never should).Hope that helps.