c++中支持仅能指向类成员的指针,对这种类型的指针进行数据的提取操作时,可使用如下两种类型的操作符:成员对象选择操作符.* 和 成员指针选择操作符->*
例一:
1 #include <iostream> 2 using namespace std; 3 struct C 4 { 5 int x; 6 float y; 7 float z; 8 }; 9 int main() 10 { 11 float f; 12 int* i_ptr; 13 14 C c1, c2; 15 16 float C::*f_ptr; // a pointer to a float member of C 17 f_ptr = &C::y; //point to C member y 18 c1.*f_ptr = 3.14; // set c1.y = 3.14 19 c2.*f_ptr = 2.01; // set c2.y = 2.01 20 21 f_ptr = &C::z; // point to C member z 22 c1.*f_ptr = -9999.99; //set c1.z = -9999.99 23 24 f_ptr = &C::y; //point to C member y 25 c1.*f_ptr = -777.77; // set c1.y 26 27 f_ptr = &C::x; // ****Error: x is not float**** 28 29 f_ptr = &f; // ****Error: f is not a float member of C**** 30 31 i_ptr = &c1.x; //c1.x is an int 32 33 //... 34 35 return 0; 36 }
例二:定义和使用指向成员函数的指针
1 #include <iostream> 2 using namespace std; 3 4 struct C 5 { 6 int x; 7 short f(int){//....}; 8 short g(int){//....}; 9 }; 10 11 int main() 12 { 13 short s; 14 C c; 15 short (C::*meth_ptr) (int); 16 meth_ptr = &C::f; 17 18 s = (c.*meth_ptr)(8); 19 C* ptr = &c; 20 s = (ptr->*meth_ptr)(9); 21 meth_ptr = &C::g; 22 s = (c.*meth_ptr)(10); 23 s = (ptr->*meth_ptr)(11); 24 return 0; 25 }