class operators

Hallo!
My question is the following:
When I define a class, I can define, for example, an operator+ as a member function of that class, but I can't define an operator<< as a member function. I don't understand why.
Waiting for a kindly replay.
Regards.

Of course you can! If you are having trouble making it work, post some simple code illustrating what you are trying to do, and someone will likely be able to help you out.

--Rollie
if you mean the stream operator <<, you'll need to make it a friend function since the left operand would be a stream.
Member binary operators always take a class object as left operand
operator<<, like all other operators, can be implemented as members.
If you make operator<<() a member function of MyType then it wall support this kind of operation:

1
2
3
4
5
6
7
8
9
struct MyType
{
    MyType& operator<<(int a); 
};

MyType m;


m << 1;


It allows you to use the << operator to output objects to objects of your class MyType, but NOT to std::ostream.

If you want to make the left side of the << operator something different from your class MyType, then it needs to be an external function:

1
2
3
4
5
6
std::ostream& operator<<(std::ostream& os, const MyType& m);

std::ostream os;

os << MyType() << std::endl;


Now you can send objects of your class MyType to a std::ostream object.



Your answers helped me to understand.
Thank you.
Topic archived. No new replies allowed.