When I did an exercise of class about complex number in C++ Primer Plus,the ideal effect is to input a complex number a+bi and output a complex number a+bi.
But I encountered a problem:the compilation error is so many that I can't list.
//This is the defination
1.istream& operator>>(istream& is, complex const&a) {
is >> a.real>>"+">> a.imag>>"i";
return is;
}
2.ostream& operator<<(ostream& os, complex const&a) {
os << a.real << "+" << a.imag << "i";
return os;
}
//the relevant class:
class complex {
private:
double real;
double imag;......
}
I want to know the difference of operator overloading between >> and<<, what's wrong with the code,and how to use>>to input const char like 'i'or'+'or other alternative method.
Implemention:I took some advice from you,and I'm sorry that I forget to add standard Header File in my "mycomplex.h"File. This is part of my modified code.
std::istream& operator>>(std::istream& is, complex &a) {//Aovid using "using namespace std".
char x1='\0', x2='\0';//Using nonconst variable after ">>"
is >> a.real >> x1;
if (x1 == '-')//Consider a value with anegative imaginary part
a.imag = -a.imag;
is>> a.imag >> x2;
if ((x1 != '+'&&x1!='-') || x2 != 'i')//Check if it's in a relevant form
std::cout << "Argument error!";
return is;
}
std::ostream& operator<<(std::ostream& os, const complex a) {
return os << a.real << "+" << a.imag << "i";
}
Finally,thanks for your contributions! :)