How to define class operator << in C ++
For a class like:
class Person { private: char *name; public: Person() { name = new char[20]; } ~Person() { delete [] name; } }
I want to print to print the name from an instance of this example using a statement like the following:
cout << myPerson << endl;
What do I need to do to define an inference statement <<
for this class?
+1
lupital
source
share
2 answers
Define a member function print () that takes an ostream value as an argument. Then let the overloaded operator <<call this member function. This way, you can avoid using a friend. Example:
void YourClass::print(ostream& out) const { //implement printing ... } ostream& operator<<(ostream& out, const YourClass& m) { m.print(out); return out; }
+3
source share