規則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.2cto.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