+ 2

{Block that contains ' &operator ' and ' *this ' } // What are their roles?

#include <iostream> using namespace std; class MyClass { public: MyClass&operator()(int a, int b) { // what is '&operator' used for? x=a; y=b; return *this; } void printInfo() { cout << x << y; } private: int x, y; }; int main() { MyClass obj; obj ( 1 , 2 ); obj.printInfo(); return 0; } // outputs 12 It appears that ' return *this; ' returns both the values of x and y. What does ' &operator ' do? Does it have to be paired with ' *this ' for the block to successfully return a value? How come the output is the same with or without the '&' sign?

9th Aug 2020, 1:01 AM
Solus
Solus - avatar
1 Odpowiedź
+ 2
Myclass& operator ()(int a,int b) Through this line you are implementing a concept called "operator overloading". Here you are overloading " () " operators. The "&" symbol simply means that the function will return object by reference which in this perticular case doesn't make any difference as you are returning a pointer. Learn more about operator overloading here👇 http://www.cplusplus.com/doc/tutorial/templates/ The keyword "this" represents a pointer to the object whose member function is being executed. It is used within a class's member function to refer to the object itself. Learn more about "this" pointer here👇 https://www.geeksforgeeks.org/this-pointer-in-c/
9th Aug 2020, 2:19 AM
Arsenic
Arsenic - avatar