指向对象成员的指针,包括指向对象成员函数的指针和指向对象成员变量的指针。
特别注意:定义指向成员函数的指针时,要标明指针所属的类。
#include <iostream>
using namespace std;
class A
{
public:
int var1, var2;
static int x;
static int get() {
return 100;
}
int add(){
return var1 + var2;
}
};
int main()
{
A ex;
ex.var1 = 3;
ex.var2 = 4;
int *p = &ex.var1; // 指向对象成员变量的指针
cout << *p << endl;
int (A::*fun_p)();//定义一个函数指针类型,我的理解这个指针是记录类成员函数的名字,或者理解实例的地址便宜,但是具体绑定需要依赖实例。
int (*fun_q)();
fun_p = &A::add; // 指向对象非静态成员函数的指针 fun_p
fun_q = A::get; // 指向对象静态成员函数的指针 fun_q
cout << (ex.*fun_p)() << endl;
cout << (*fun_q)() << endl;
return 0;
}
参考链接:https://leetcode.cn/leetbook/read/cmian-shi-tu-po/vdlag5/
来源:力扣(LeetCode)