エントリーから熟練者へのC ++-クラスメンバーへのポインター

クラスメンバーへのポインタ

メンバー変数へのポインター

#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;
}


出力

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

メンバー関数へのポインター

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;
}

静的メンバーへのポインター


  • クラスの静的データメンバーへのポインター静的データメンバーへのポインターの定義と使用、通常のポインターと同じです。定義時にクラスに関連付ける必要はなく、使用時に特定のオブジェクトに関連付ける必要もありません。
  • クラスの
    静的メンバー関数へのポインター静的メンバー関数へのポインターは、通常のポインターと同じです。定義時にクラスに関連付ける必要はなく、使用時に特定のオブジェクトに関連付ける必要もありません。
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();
}

出力

100
100

おすすめ

転載: blog.csdn.net/e891377/article/details/108677012
おすすめ