I have a class, and would like the class to return a member when referenced.
Desired syntax because my question was unclear:
SomeClass some_var = "Something I want to be returned from SomeClass when referenced";
cout << some_var; // How would this return the string I provided?
I know this is a very simple example, and this could be replaced with a std::string, but how would I do this?
Basically, you need to add something that will handle this you need to “overload” or create a custom case for your class to handle outputs (<< operator). Here you go:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}