+ 1

Plz answer?

please explain this code, what is the purpose of that friend overloaded function, i mean why only overload that with friend, https://www.sololearn.com/post/15495/?ref=app

12th Jul 2018, 9:05 PM
Wasim Abbasi
Wasim Abbasi - avatar
2 Answers
+ 5
The purpose of overloading the << operator is to have an easy way of printing your object to the console. Its definition would probably look something like this: ostream& Complex::operator<<(ostream& o, const Complex& c) { o << c.x << "/" << c.y; return o; } This way, you can write cout << c; in your code when you want to print the number (where c is any object of type Complex). But as you can see, the function accesses private members, thus it is a friend. If you don't want it to be a friend function, you can make get() methods for your private variables and call those instead. E.g. o << c.getX() ...
12th Jul 2018, 9:25 PM
Shadow - avatar
14th Jul 2018, 9:07 PM
Wasim Abbasi
Wasim Abbasi - avatar