|
发表于 2012-8-20 17:32:45
|
显示全部楼层
但是实际上,通过程序也是可以通过函数指针的方式访问普通类成员函数。
如下面这个例子:- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- class A
- {
- private:
- int a;
- public:
- A(int _a): a(_a)
- {}
- void fun1() const
- {
- std::cout << "this is fun1, a = " << a << std::endl;
- }
- int fun2() const
- {
- std::cout << "this is fun2, a = " << a << std::endl;
- return 0;
- }
- static void fun3(const A& _a)
- {
- std::cout << "this is fun3, ";
- _a.fun1();
- }
- friend void fun4(const A& _a)
- {
- std::cout << "this is fun4, a = " << _a.a << std::endl;
- }
- };
- typedef void (A::*pcf)()const;
- void call_A(pcf pF, const A& _a)
- {
- (_a.*pF)();
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- A a(10);
- call_A(&A::fun1, a);
- return 0;
- }
复制代码 在这个例子中,fun1是类A的成员函数,我们通过typedef void (A::*pcf)()const; 定义了一个pcf函数指针指向了A::fun1()就可以直接调用。 |
|