class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << ai << ")";
}
So you can output instances of the class on the stream:
A x = ...;
std::cout << x << std::endl;
If your operator << wants to print out the inside of class A, and really needs to access its private and protected members, you can also declare it as a friend function :
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << aj << ")";
}
I want to control the content written to the stream, i.e. cout, to obtain objects of a custom class. Is this possible in C? In Java, you can override the toString() method for similar purposes.
In C, you can overload the operator< So you can output on the stream Examples of classes:class A {
public:
int i;
};
std::ostream& operator<<(std: :ostream &strm, const A &a) {
return strm << "A(" << ai << ")";
}
A x = ...;
std::cout << x << std::endl;
If your operator << wants to print out the inside of class A, and really needs to access its private and protected members, you can also declare it as a friend function:
class A {< br />private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std: :ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << aj << ")";
}