Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to overload the stream operators << >> for my class?

I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the moment, for the "get from" operator, I have a definition

istream& operator>>(istream& is, Thing& thing) { // etc...

which works. It's not mentioned in the definition of the Thing class. I want it to be able to access members of my Thing class in its implementation - how do I do this?

like image 309
ghallio Avatar asked Feb 28 '10 17:02

ghallio


People also ask

What is the correct way to overload operator?

In case of operator overloading all parameters must be of the different type than the class or struct that declares the operator. Method overloading is used to create several methods with the same name that performs similar tasks on similar data types.

Can we overload << operator?

We can overload the '>>' and '<<' operators to take input in a linked list and print the element in the linked list in C++. It has the ability to provide the operators with a special meaning for a data type, this ability is known as Operator Overloading.

Can we overload << operator in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions.

Which function overloads the << operator in Python?

The operator overloading in Python means provide extended meaning beyond their predefined operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class and "str" class.


1 Answers

Your implementation is fine. The only additional step you need to perform is to declare your operator as a friend in Thing:

class Thing {
public:
  friend istream& operator>>(istream&, Thing&);
  ...
}
like image 101
vladr Avatar answered Oct 11 '22 17:10

vladr