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!
Output streams use the insertion ( << ) operator for standard types. You can also overload the << operator for your own classes.
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.
We use extraction operator (<<) for the object (cout) of output stream. So this is the operator that gets used.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With