指向成员变量和成员方法的指针
指向成员变量的指针
class Test {
public:
int ma;
static int mb;
};
int Test::mb;
int main() {
//类对象的成员变量指针不是普通的指针,需要加入类名限定符
//类的静态成员变量指针不针对某一个特定对象,使用普通指针
int* p = &Test::mb;
int Test::* q = &Test::ma;
Test t1;
Test *t2 = new Test();
t1.ma = 1;
t1.*q = 2;
cout << t1.ma << endl;
t2->ma = 1;
t2->*q = 2;
cout << t2->ma << endl;
//t2->*p = 2; //错误
*p = 2;
cout << Test::mb << endl;
}
指向成员方法的指针
class Test {
public:
void func() {
cout << "func" << endl;
}
static void sfunc() {
cout << "sfunc" << endl;
}
int ma;
static int mb;
};
int Test::mb;
int main() {
Test t1;
Test *t2 = new Test();
//普通成员函数指针是针对对象的,要加上类名限定符
//静态成员函数指针不针对某一个特定对象,使用普通指针
void(Test:: * func_ptr)() = &Test::func;
void(* func_sptr)() = &Test::sfunc;
(t1.*func_ptr)();
(t2->*func_ptr)();
(*func_sptr)();
}
标签:15,cout,int,成员,Test,ma,指针
From: https://www.cnblogs.com/sio2zyh/p/17967126