Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't cout << work with overloaded * operator?

I'm creating my first class, mainly guided by Overland's C++ Without Fear. I've made the overloaded friend ostream operator<<, which works fine. I've also overloaded the * operator, and that works fine. What doesn't work is when I try to output the result of the * operator directly:

BCD bcd(10);  //bcd is initialised to 10
BCD bcd2(15); //bcd2 is initialised to 15
cout << bcd;  //prints 10
bcd2 = bcd2 * 2; //multiplies bcd2 by 2
cout << bcd2; //prints 30

cout << bcd * 2 //SHOULD print 20, but compiler says
//main.cpp:49: error: no match for 'operator<<' in 'std::cout << BCD::operator*(int)(2)'

For info, here are my prototypes:

BCD operator*(int z);
friend ostream &operator<<(ostream &os, BCD &bcd);

As far as I can tell, operator* returns a BCD, so operator<< should be able to print it. Help please!

like image 608
Skilldrick Avatar asked Jan 16 '09 20:01

Skilldrick


People also ask

Can << operator be overloaded?

Output streams use the insertion ( << ) operator for standard types. You can also overload the << operator for your own classes.

Can << operator be overloaded in C++?

Input/Output Operators Overloading in C++ C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object.

Which operator is overloaded for cout operation?

We use extraction operator (<<) for the object (cout) of output stream. So this is the operator that gets used.

What is << operator in cout?

In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class. 2) These operators must be overloaded as a global function ...


1 Answers

What's happening is that bcd * 2 is generating a temporary BCD, which cannot bind to a BCD &. Try replacing the << operator with one of these:

friend ostream &operator<<(ostream &os, const BCD &bcd);

or

friend ostream &operator<<(ostream &os, BCD bcd);

or even

friend ostream &operator<<(ostream &os, const BCD bcd);

The first one works, since binding a temporary variable to a constant reference is explicity allowed, unlike binding to a non-const reference. The other ones work by making a copy of the temporary variable.

Edit: As noted in the comments - prefer the const & version in most cases, since modifying an object in a streaming operator will be surprising to anyone using your class. Getting this to compile may require adding const declarations to your classes member function where appropriate.

like image 139
Eclipse Avatar answered Sep 30 '22 05:09

Eclipse