Feb 11, 2020 at 3:22am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14
struct ptr {
int operator [](int a){
return 3;
}
};
int main() {
ptr x;
cout << x[1];
}
I like this "operator thing", but how can do the same without the brackets? E.g. "cout << x" instead of "cout << x[n]" and get the same output.
Last edited on Feb 11, 2020 at 3:22am UTC
Feb 11, 2020 at 3:33am UTC
Tell the compiler what to do when it sees
standard_output_stream << your_class
By overloading operator<< for the involved types:
std::ostream& operator<<(std::ostream& os, ptr p) { return os << 3; }
Feb 11, 2020 at 3:54am UTC
Thanks mbozzi, it works great outside the struct. Is it possible to have it inside the struct somehow so I can access a member that way?
Last edited on Feb 11, 2020 at 3:58am UTC
Feb 11, 2020 at 4:24am UTC
No: if it was a member function, it would need to be a member of
std::ostream . This isn't possible.
However, you can make it a
friend of your own class:
1 2 3 4 5
struct ptr
{
friend std::ostream& operator <<(std::ostream& os, ptr)
{ return os << 3; }
};
Friend functions are not member functions, but they have access to the protected and private members of the classes they're friends with.
Last edited on Feb 11, 2020 at 4:31am UTC