应用C++成员指针需要遵守的两个规则
规则1:*需要与间接引用的对象结合,因为类内部是没有地址的,所以成员指针只是代表对象内一定的偏移
规则2: 当获取成员函数的地址(偏移地址)时,符号&是必要的,这与非成员函数指针的用法不同
用例1:
//: PointerToMemberData.cpp
#include <iostream>
using namespace std;
class Data
{
public:
int a, b, c;
void print() const
{
cout << "a = " << a << ", b = " << b
<< ", c = " << c << endl;
}
};
int main()
{
Data d, *dp = &d;
int Data::*pmInt = &Data::a;
dp->*pmInt = 47; //规则1
pmInt = &Data::b;
d.*pmInt = 48;
pmInt = &Data::c;
dp->*pmInt = 49; //规则1
dp->print();
}
用例2: www.zzzyk.com
//: PointerToMemberFunction.cpp
#include <iostream>
using namespace std;
class Widget
{
public:
void f(int) const { cout << "Widget::f()\n"; }
void g(int) const { cout << "Widget::g()\n"; }
void h(int) const { cout << "Widget::h()\n"; }
void i(int) const { cout << "Widget::i()\n"; }
};
int main()
{
Widget w;
Widget* wp = &w;
void (Widget::*pmem)(int) const = &Widget::h; //规则2
(w.*pmem)(1); //规则1
(wp->*pmem)(2); //规则1
}
用例3:
//: PointerToMemberFunction2.cpp
#include <iostream>
using namespace std;
class Widget
{
void f(int) const { cout << "Widget::f()\n"; }
void g(int) const { cout << "Widget::g()\n"; }
void h(int) const { cout << "Widget::h()\n"; }
void i(int) const { cout << "Widget::i()\n"; }
enum { cnt = 4 };
void (Widget::*fptr[cnt])(int) const;
public:
Widget()
{
fptr[0] = &Widget::f; //规则2
fptr[1] = &Widget::g;
fptr[2] = &Widget::h;
fptr[3] = &Widget::i;
}
void select(int i, int j)
{
if(i < 0 || i >= cnt)
return;
(this->*fptr[i])(j); //规则1,this必不可少
}
int count() { return cnt; }
};
int main()
{
Widget w;
for(int i = 0; i < w.count(); i++)
w.select(i, 47);
}
作者 yucan1001
补充:软件开发 , C++ ,