I have the following piece of code:
class Student {
public:
Student(){}
void display() const{}
friend istream& operator>>(istream& is, Student& s){return is;}
friend ostream& operator<<(ostream& os, const Student& s){return os; }
};
int main()
{
Student st;
cin >> st;
cout << st;
getch();
return 0;
}
I have tried myself when omitting the friend keywords to make the operators become the member function of the Student class, then the compiler would produce “binary 'operator >>' has too many parameters“. I have read some document saying that happened because all member functions always receive an implicit parameter “this” (that’s why all member functions can access private variables).
Based on that explanation, I have tried as follows:
class Student {
public:
Student(){}
void display() const{}
istream& operator>>(istream& is){return is;}
ostream& operator<<(ostream& os){return os; }
};
int main()
{
Student st;
cin >> st;
cout << st;
getch();
return 0;
}
And got the error message: “error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'Student' (or there is no acceptable conversion)“
Can anyone give me a clear explanation, please?
You can’t say that the function is a friend function, and then include the function in-line. The friend keyword implies that the function is not defined in the class, but it can access all the private and protected variables of the class. Change your code to:
Look at http://www.java2s.com/Code/Cpp/Overload/Overloadstreamoperator.htm for another example.
With << and >>, the left hand operand is always a file stream, so you cannot overload them within your actual class (it’d technically have to go in the file stream class).