- 论坛徽章:
- 0
|
- #include <iostream>
- using namespace std;
- class A; //前制声明
- typedef void (A::*FUN)(); //定义了一个成员函数指针类型,该类型的函数定义在class A范围内,接受void参数,返回void类型
- class A
- {
- friend void fun(A&, int); //要访问类的私有成员,必须声明该函数为类的友元,同时,为了存取对象的数据,必须传入一个对象的实例作为参数
- public:
- void init();
- private
- void fun1( )
- {
- cout << "func1" << endl;
- }
- void fun2( )
- {
- cout <<"func2" << endl;
- }
- private:
- FUN m_funs[2];
- };
- //想知道你这样做的目的是什么?
- //作为一个成员函数,它实际上有在编译期内确定的意味,所以,A::fun1是每个类一个的,而不应当是每个实例一个的,也就是说,m_funs应当是一个static的成员变量(per class),而不是per instance。
- void A::init( )
- {
- m_funs[0]= &A::fun1; //应当是类A域里的函数的地址
- m_funs[1] = &A::fun2;
- }
- void fun(A& a, int i)
- {
- (a.*(a.m_funs[i]))(); //m_funs是对象a中的一个数组,该数组的元素是一个FUN类型的指针
- }
- int main()
- {
- A a;
- a.init();
- fun(a, 0);
- fun(a, 1);
- return (0);
- }
复制代码 |
|