【求教】请问大家:指向函数的指针作为一个类的成员,如果通过对象调用它,实现调用所指向的函数的目的?
问题RT,下面给出自己编写的程序(一部分)作为错误的例子,希望大神帮忙修改,最好能有解释,谢谢啦~~~~!!!!#include <iostream>
#include <string>
class Equation
{
private:
int answer,m;
void (*mode[3])(); //定义了一个指向函数的指针数组
public:
Equation();
void setmode();
void addition();
void subtraction();
void multiplication();
int getanswer () const {return answer;}
void *run () const {return mode[m];} //定义了一个指针类的函数,我希望通过这个指针函数来调用那个指针,从而调用所指向的函数
};
#endif
#include "Random.h"
#include "Equation.h"
#include <string>
#include <iostream>
using namespace std;
namespace
{ const string CORRECT_INFO[]={"Good job!","Correct,again!","You are so clever!","Wow,a talent!","You did it, Congratulations!"};
const string WRONG_INFO[]={"Just carelessness,cheer up!","What a pity!","Sorry, you are fail."};
};
int main()
{ int score,ans,i,j;
char whethergo;
Equation equ;
cout<<"Welcome to Guess!"<<endl;
for (i=1;i<=10;i++)
{ cout<<"Question "<<i<<endl;
*equ.run(); //调用了那个指针类的函数,编译后报错
for (j=0;j<3;j++)
{ cin>>ans;
if (ans==equ.getanswer())
{ Random r(4);
score+=10;
cout<<"Right!"<<endl<<CORRECT_INFO[r.getr()]<<endl;
break;
}
else
{ Random r(2);
cout<<"Wrong"<<endl<<WRONG_INFO[r.getr()]<<endl;
}
}
if (j==3)
cout<<"Sorry, you have no chances."<<endl;
cout<<"Go ahead?(Y/N)";
cin>>whethergo;
if (whethergo=='N')
{ cout<<"Your score is "<<score<<endl;
break;
}
}
if (i==11)
cout<<"You have complete the game!"<<endl<<"Your score is "<<score<<endl;
cout<<"Thank you for your support! Press any key to quit.";
cin>>i;
return 0;
}
--------------------Configuration: main - Win32 Debug--------------------
Compiling...
main.cpp
F:\study\VC++\guess\main.cpp(17) : error C2100: illegal indirection
执行 cl.exe 时出错.
main.obj - 1 error(s), 0 warning(s)
我的最终目的是在主程序中设法调用指向函数的指针*mode[i],通过它运行所指向的程序。至于那个指针类的函数(外部接口)*run()是我自己理解的,不知道这样的做法对不对。我是初学者,真心求教~!!谢谢~~~~~~!!