C++ from entry to proficient-pointers to class members

Pointer to class member

Pointer to member variable

#include <iostream>
#include <string>
using namespace std;

class A{
    
    
public:
	A(int param){
    
    
		mParam = param;
	}
public:
	int mParam;
};

void test(){
    
    
	A a1(100);
	A* a2 = new A(200);
	int* p1 = &a1.mParam;
	int A::*p2 = &A::mParam;

	cout << "*p1:" << *p1 << endl;
	cout << "a1.*p2:" << a1.*p2 << endl;
	cout << "a2->*p2:" << a2->*p2 << endl;
}



int main() {
    
    

    test();

    return 0;
}


Output

*p1:100
a1.*p2:100
a2->*p2:200

Pointer to member function

class A{
    
    
public:
	int func(int a,int b){
    
    
		return a + b;
	}
};

void test(){
    
    
	A a1;
	A* a2 = new A;

	//初始化成员函数指针
	int(A::*pFunc)(int, int) = &A::func;
	//指针解引用
	cout << "(a1.*pFunc)(10,20):" << (a1.*pFunc)(10, 20) << endl;
	cout << "(a2->*pFunc)(10,20):" << (a2->*pFunc)(10, 20) << endl;
}

Pointer to static member

  • Pointers
    to static data members of the class The definition and use of pointers to static data members are the same as ordinary pointers. They do not need to be associated with the class when they are defined, and they do not need to be associated with specific objects when they are used.
  • A pointer
    to a static member function of a class The pointer to a static member function is the same as an ordinary pointer. It does not need to be associated with the class when it is defined, and it does not need to be associated with a specific object when it is used.
class A{
    
    
public:
	static void dis(){
    
    
		cout << data << endl;
	}
	static int data;
};

int A::data = 100;

void test(){
    
    
	int *p = &A::data;
	cout << *p << endl;
	void(*pfunc)() = &A::dis;
	pfunc();
}

Output

100
100

Guess you like

Origin blog.csdn.net/e891377/article/details/108677012