Reputation: 5239
I have overloaded <<
in my code as a friend function. Even after using braces while cascading there is still the error
error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits =
std::char_traits<char>]((* & std::cout), ((const char*)"complex conjugate is "))
<< c.myComplex::operator~()’
I have a 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 for <<
, ~
and the constructors are as 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 it in main as follows,
Line 1: std::cout << "c is " << c << "\n";
Line 2: std::cout << "a is " << a << "\n";
Line 3: ((std::cout <<"complex conjugate is ")<<(~c))<<"\n";
Line 3: std::cout <<"complex conjugate is "<<~c<<"\n";
Line 1 and 2 work fine, but Line 3 gives the error. If it can cascade for Line 1 and 2 and since ~c
also returns an ostream
why does it give an error for that?
Upvotes: 0
Views: 406
Reputation: 227438
Because your operator~()
returns by value, you are feeding a temporary object into your ostream& operator<<
here:
std::cout <<"complex conjugate is "<< ~c <<"\n";
// ^^ HERE! Temporary myComplex value.
The operator takes its 2nd argument by non-const reference myComplex&
. A non-const reference cannot bind to a temporary. Change it to
std::ostream& operator<<(std::ostream& oso, const myComplex& a);
Upvotes: 2
Reputation: 171127
Your operator <<
takes the second parameter by non-const reference, which means it can't bind to a temporary (such as the one returned by ~
). Change operator <<
to accept const myComplex&
as the second argument.
It would certainly be weird if the stream-output operator modified its argument anyway.
BTW, do you know that C++ has a built-in class std::complex
?
Upvotes: 1
Reputation: 121971
A temporary object (in this case that returned by operator~()
) cannot be bound to a non-const
reference. Change argument of operator<<()
to be a const
reference:
friend std::ostream& operator<<(std::ostream& iso,myComplex const& a);
Upvotes: 3
Reputation: 122391
Use const myComplex &
instead of myComplex &
:
friend std::ostream& operator<<(std::ostream& iso, const myComplex& a);
^^^^^
And change the implementation, of course.
Upvotes: 2