To use std::cout for printing a custom object, we need to overload the << operator. In most cases, we require the friend keyword to access non-public members of the class.
#include <iostream>
using namespace std;
class A {
int val;
public:
A(int v) : val(v) {}
friend ostream& operator<<(ostream& os, const A& obj) {
os << obj.val;
return os;
}
};
int main() {
A obj(42);
cout <<"Value = "<< obj << endl; // Output: Value: 42
return 0;
}
Top comments (2)
std::cout
. You can use anyostream
.<<
must be a non-member function — which is why you needfriend
.you are right^^