c++中的成员选择符

时间:2023-03-09 15:07:56
c++中的成员选择符

c++中支持仅能指向类成员的指针,对这种类型的指针进行数据的提取操作时,可使用如下两种类型的操作符:成员对象选择操作符.* 和 成员指针选择操作符->*

例一:

 #include <iostream>
using namespace std;
struct C
{
int x;
float y;
float z;
};
int main()
{
float f;
int* i_ptr; C c1, c2; float C::*f_ptr; // a pointer to a float member of C
f_ptr = &C::y; //point to C member y
c1.*f_ptr = 3.14; // set c1.y = 3.14
c2.*f_ptr = 2.01; // set c2.y = 2.01 f_ptr = &C::z; // point to C member z
c1.*f_ptr = -9999.99; //set c1.z = -9999.99 f_ptr = &C::y; //point to C member y
c1.*f_ptr = -777.77; // set c1.y f_ptr = &C::x; // ****Error: x is not float**** f_ptr = &f; // ****Error: f is not a float member of C**** i_ptr = &c1.x; //c1.x is an int //... return ;
}

例二:定义和使用指向成员函数的指针

 #include <iostream>
using namespace std; struct C
{
int x;
short f(int){//....};
short g(int){//....};
}; int main()
{
short s;
C c;
short (C::*meth_ptr) (int);
meth_ptr = &C::f; s = (c.*meth_ptr)();
C* ptr = &c;
s = (ptr->*meth_ptr)();
meth_ptr = &C::g;
s = (c.*meth_ptr)();
s = (ptr->*meth_ptr)();
return ;
}