-3
fstream& operator>> (fstream & in, class& obj);

fstream& operator<< (fstream & out, class& obj);

Is this overloading legal or not?
And what is it's solution?

Actually l am using files in a program with the help of fstream class objects. So I need to overload >>&<< operators so that such statements can work.

File>>obj; File<

But would ifstream& operator >> (ifstream & , classname& obj) ofstream& operator >> (ofstream & , classname& obj)

Work for fstream objects?

  • 3
    Is this a question from a quiz or homework? – StoryTeller - Unslander Monica Jun 19 '18 at 06:07
  • 2
    `class` is a language keyword, not a type. So your examples as written are not valid C++. If you replace `class` with the name of a valid type for which `fstream` does not already overload the operators, then your examples would be valid declarations - assuming a `using namespace std` is in effect, and not causing ambiguity. – Peter Jun 19 '18 at 06:10
  • Related: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/) – Remy Lebeau Jun 19 '18 at 06:17

2 Answers2

1

Legal, but you should use the more general forms:

istream& operator>>(istream& in, t& obj);
ostream& operator<<(ostream& out, const t& obj);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
krisz
  • 2,686
  • 2
  • 11
  • 18
0

In operator overloading, if an operator is overloaded as member, then it must be a member of the object on left side of the operator.The operators ‘<<' and '>>' are called like 'cout << ob1' and 'cin >> ob1'. So if we want to make them a member method, then they must be made members of ostream and istream classes, which is not a good option most of the time. Therefore, these operators are overloaded as global functions with two parameters, cout and object of user defined class.