/*
*测试成员函数指针数组的小程序
*/
#include <iostream>
using namespace std;
class Test
{
public:
Test();
~Test();
private:
void add5(){ res+=5;}
void add6(){ res+=6;}
void (Test::*add[2])();//这个2至关重要,在VC下没写会报错,但在QT里没报,但析构时出错!
public:
void DoAddAction();
void Display();
private:
int res;
};
Test::Test()
{
add[0]=&Test::add5;//注意这里的写法
add[1]=&Test::add6;
res=0;
}
Test::~Test()
{
}
void Test::DoAddAction()
{
for (int i=0;i<2;i++)
{
(this->*add[i])();//使用类成员函数指针必须有“->*”或“.*”的调用
}
}
void Test::Display()
{
cout<<"The res is:"<<res<<endl;
}
int main()
{
Test * test=new Test();
test->DoAddAction();
test->Display();
delete test;
return 0;
}
转自:http://www.cppblog.com/dragon/archive/2010/12/02/135250.html 谢谢这位仁兄!