指向类成员的指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Test { public: void func() { cout<<"call Test::func"<<endl; } static void static_func() { cout<<"Test::static_func"<<endl; } int ma; static int mb;
};
int Test::mb=0;
int main() { Test t1; Test *t2=new Test();
int Test::*p=&Test::ma; t1.*p=20; t2->*p=30; delete t2;
int *p1=&Test::mb; *p1=40;
return 0;
}
|
在C++中,成员指针是一种特殊的指针类型,它指向类的成员(可以是数据成员或成员函数),而不是指向内存地址。成员指针需要与特定的对象实例结合使用,才能真正访问或修改该对象的成员。
指向成员方法的指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Test { public: void func() { cout<<"call Test::func"<<endl; } static void static_func() { cout<<"Test::static_func"<<endl; } int ma; static int mb;
}; int Test::mb=0; int main() { Test t1; Test *t2=new Test(); void(Test::*pfunc)()=&Test::func; (t1.*pfunc)(); (t2->*pfunc)(); void(*pfunc2)() = &Test::static_func; (*pfunc2)(); }
|
总结
- 静态成员变量是在类的所有对象之间共享的变量,它们存储在数据段中
- 静态成员函数不依赖于具体的对象实例,因此它们的指针类型不需要包含类类型的限定符
即静态的指针不需要类型限定符
普通指针(如 int p)可以用于指向静态成员变量,因为静态成员变量属于类本身,而不是某个特定的对象实例。
成员指针(如 int Test:: p)用于指向类的非静态成员变量或成员函数,并且需要与具体的对象实例结合使用。它们不适合用于指向静态成员变量。
成员函数指针指向某个成员方法:
void(Test::*pfunc)()=&Test::func;