Understanding Member-Pointer Operators

I copied this program from a C ++ practice tutorial. What is going on behind the scenes?

Expected Result:

sum = 30 sum = 70

#include<iostream> using namespace std; class M { int x; int y; public: void set_xy(int a, int b) { x=a; y=b; } friend int sum(M m); }; int sum (M m); //so far so good, problem begins from here. what happening after here? { int M ::*px = &M ::x; int M ::*py = &M ::y; M *pm =&m; int s= m.*px+ pm->*py; return s; } int main() { M n; void (M :: *pf)(int, int) = &M ::set_xy; (n.*pf)(10, 20); cout <<"sum=" << sum(n) << endl; M *op= &n; (op-> *pf)(30,40); cout << "sum=" << sum(n)<< endl; cin.ignore(); getchar(); return 0; } 
+6
source share
3 answers

The problem is with extra spaces in op-> *pf :

  (op->*pf)(30,40); // ok 

I think @fefe probably said the reason in the comment. ->* is the only operator similar to .* . So, if these 2 are separated, then this will lead to a different syntax that gives a compiler error.

+1
source

Look at the pointer to the class data . And for the error, → * is an operator, you cannot put a space between them.

+1
source

iammilind put me on a mistake; op-> *pf must be changed so that you have ->* together as one operator - a pointer to a member operator (could not find a better link). Spaces in op ->* pf are acceptable.

The same goes for i++ ; ++ is the only operator and raises an error if you try to use i+ + .

Now what is he doing. An example is a pointer to a member function. pf declared as a member function of class M , which takes two int arguments with the return type void . It is initialized to point to the function M::set_xy .

Inside main :

  • n is of type M , therefore, to use pf to call set_xy of n , you must use the operator .* : (n.*pf)(10, 20); . This is equivalent to n.set_xy(10, 20); .

  • Since op is of type M* (a pointer to an object M ), you will need to use the ->* operator and call the function pointed to by pf , like: (op->*pf)(30, 40); , which is equivalent to op->set_xy(30, 40);

Inside sum :

  • Examples are simply pointers to member / instance variables, and not to member functions. It just demonstrates how you add mx and my together with these types of pointers.
+1
source

Source: https://habr.com/ru/post/904053/


All Articles