c++ How to not use friend declaration when equipping a class with `operator<<`
Here's a way to equip a class with the operator<<
without using the friend
declaration:
- Create a class with private members and a public function to access those members:
class MyClass {
private:
int data;
public:
MyClass(int d) : data(d) {}
int getData() const { return data; }
};
- Define the
operator<<
function outside the class as a non-member function:
#include <iostream>
void operator<<(std::ostream& os, const MyClass& obj) {
os << obj.getData();
}
This implementation allows operator<<
to access the class's private members through the public member function getData()
.