c++ - Cascading overloaded cout operator error `No match` when used with other overloaded operators -
i have overloaded << in code friend function. after using braces while cascading there still error
error: no match ‘operator<<’ in ‘std::operator<< [with _traits = std::char_traits<char>]((* & std::cout), ((const char*)"complex conjugate ")) << c.mycomplex::operator~()’ i have class mycomplex
class mycomplex { private: float real; float imaginary; public: mycomplex(); mycomplex(float a,float b); friend std::ostream& operator<<(std::ostream& iso,mycomplex& a); mycomplex operator~() const; }; the overload <<, ~and constructors follows,
std::ostream& operator<<(std::ostream& oso,mycomplex& a) { oso<<a.real<<" + "<<a.imaginary<<"i"<<std::endl; return oso; } mycomplex mycomplex::operator~() const { return mycomplex(this->real,-1*this->imaginary); } mycomplex::mycomplex(float a,float b) { real = a; imaginary = b; } i use in main follows,
line 1: std::cout << "c " << c << "\n"; line 2: std::cout << "a " << << "\n"; line 3: ((std::cout <<"complex conjugate ")<<(~c))<<"\n";
line 3: std::cout <<"complex conjugate "<<~c<<"\n"; line 1 , 2 work fine, line 3 gives error. if can cascade line 1 , 2 , since ~c returns ostream why give error that?
because operator~() returns value, feeding temporary object ostream& operator<< here:
std::cout <<"complex conjugate "<< ~c <<"\n"; // ^^ here! temporary mycomplex value. the operator takes 2nd argument non-const reference mycomplex&. non-const reference cannot bind temporary. change to
std::ostream& operator<<(std::ostream& oso, const mycomplex& a);
Comments
Post a Comment