Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you format operator<< for classes?

As in, should the operator>> match the operator<< ?

Database Example:

If the operator>> reads in something of the following format:

2
Joe 500 20 1
Bob 250 30 0

should the operator<< output that? Or something like this:

Record: 1/2
Name: Joe
Balance: 500
Transactions: 20
Premium Account: Yes

And then have a separate writeFile() function?

I know either would work, but what is the "accepted standard"?

like image 832
cactusbin Avatar asked Jun 21 '10 01:06

cactusbin


People also ask

Why the operator << function could not be written as a member of the class?

The operator<< function can't be a member of your own class, because the left-hand operand is an ostream object. 2. The first parameter has to be a reference-type parameter because you want os to be the very same stream object that the operator is applying to, and not a copy of it.

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.

What is the advantage of overloading the << and >> operators?

By overloading the operators, we can give additional meaning to the operators like +-*/=.,= etc., which by default are supposed to work only on standard data types like int, float, char, void etc. It is an essential concept in C++.


2 Answers

If you have an istream operator>> overload for a type that reads data in a particular format, then if you implement an ostream operator<< overload for the same type, it should output in the same format (otherwise, it could get quite confusing).

like image 136
James McNellis Avatar answered Sep 28 '22 08:09

James McNellis


This kind of operator overloading is IMO a big misuse and misconception. Use overloading where it really makes some sense.

For debug purposes, have toString() and override << to call it. Do not override >> at all.

>> and << generally serve for sending serialized data to streams, not for communication with user.

My 2 eurocents.

like image 33
Ondra Žižka Avatar answered Sep 28 '22 08:09

Ondra Žižka