I'm going through an ebook ( http://www.e-booksdirectory.com/details.php?ebook=5576) "Beginning C++ Through Game Programming." I'm at the point of overloading operators and this code gets a little cryptic to me. In the program, the << operator is overloaded. The overload function is made a friend function and is defined outside the class.
For clarity's sake, what would the same operator overload function look like if declared as a public class function?
And, how else could it be call with out using the << operator? e.g., from the C++ tutorial here:
"The function operator+ of class CVector overloads the addition operator (+) for that type. Once declared, this function can be called either implicitly using the operator, or explicitly using its functional name:
c = a + b;
c = a.operator+ (b); "
How would you call the << operator function explicitly?
//Friend Critter
//Demonstrates friend functions and operator overloading
#include <iostream>
#include <string>
usingnamespace std;
class Critter
{
//make following global functions friends of the Critter class
friendvoid Peek(const Critter& aCritter);
friend ostream& operator<<(ostream& os, const Critter& aCritter);
public:
Critter(const string& name = "");
private:
string m_Name;
};
Critter::Critter(const string& name) :
m_Name(name)
{}
void Peek(const Critter& aCritter);
ostream& operator<<(ostream& os, const Critter& aCritter);
int main()
{
Critter crit("Poochie");
cout << "Calling Peek() to access crit’s private data member, m_Name: \n";
Peek(crit);
cout << "\nSending crit object to cout with the << operator:\n";
cout << crit;
return 0;
}
//global friend function which can access all of a Critter object’s members
void Peek(const Critter& aCritter)
{
cout << aCritter.m_Name << endl;
}
//global friend function which can access all of Critter object’s members
//overloads the << operator so you can send a Critter object to cout
ostream& operator<<(ostream& os, const Critter& aCritter)
{
os << "Critter Object - ";
os << "m_Name: " << aCritter.m_Name;
return os;
}
For clarity's sake, what would the same operator overload function look like if declared as a public class function?
You cannot do that.
Operator defined inside class will have a reference to that class as left hand argument. However for IO operators left hand operand should be stream.
This is the reason why we have to define it outside class.