TL ; DR:
Write an operator<< function for your class. Then cout << can print its objects.
class Cat {
public:
string name;
Cat(string name) {
this->name = name;
}
};
ostream& operator<<(ostream& out, const Cat& cat) {
out << "Cat named " << cat.name;
return out;
}
// cout << Cat("Tom") << endl; prints Cat named Tom
Full lesson:
cout << knows how to print numbers and strings. It doesn't know your classes. So cout << tom doesn't even compile:
error: no match for 'operator<<'
In C++, << is a function named operator<<. You can add one more version of it, for your class. This is called operator overloading.
Your version takes the stream as ostream& out and the object as const Cat& cat. The & passes both without copying them. The const promises not to change the cat.
Inside, send the parts to out with <<, as you would to cout. Then return out. That lets the caller keep chaining, as in cout << tom << endl.
It works for every output stream, files too. It sits outside the class, so it reads public fields. For private fields, declare it a friend inside the class.
Your task
The Dog class below has a name and an age. Below the class, write operator<< for Dog.
It sends the name, then " is ", the age and " years old". The code in mainFunction prints two dogs.
Expected output:
Rex is 3 years old
Bella is 5 years oldFree plan: 30 tutor messages. Premium is unlimited.
