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