0

1.why the "<<" operator overloading should be a frinend function of the class 2. why "&" is used while decaring the operator

friend ostream & operator<< (ostream & output,complex com) { output << com.img << " " << com.real ; return output; } i cant understand why in the above operator loading the function must be a friend and why the address operator(&) is used befor the keyword "operator"; https://code.sololearn.com/c4h00W7t5A0H/?ref=app

18th Nov 2018, 6:15 AM
D7d77d7d77
D7d77d7d77 - avatar
3 Respuestas
+ 5
1. The operator must be a friend function because it is not a member function of the class 'complex', but needs to access private variables of the class in order to print them. If you provide getter-methods for 'img' and 'real', the need for it to be a friend would cease because then it could call the getters instead of the variables, thus no longer accessing any private variables. 2. The '&' means that you return a reference to the output stream. Without it, you would return a copy only, which means if you chained any more calls of '<<' after calling it with a complex number, they would have no effect (no output) because the original stream wouldn't be affected, just a copy of it.
18th Nov 2018, 7:14 AM
Shadow
Shadow - avatar
+ 2
This is what an overloaded output operator would look like as a member function (just an example): https://code.sololearn.com/cjD3ahyL1KoC/?ref=app That is really not what you want. The object of 'Foo' must be at the beginning of the output statement, making it look nothing like you would expect it to look. Moreover, this way you can't chain any calls to objects of 'Foo'.
18th Nov 2018, 9:20 AM
Shadow
Shadow - avatar
0
if i make it a member function , it is giving an error ,
18th Nov 2018, 7:32 AM
D7d77d7d77
D7d77d7d77 - avatar