mll*_*l36 4 c++ function-pointers class
我有一个类 say Method with multiple functions 用于解决 PDE 的不同方法,类似于下面的加、减、乘...函数。类中的另一个函数(本示例中的 DoMath)调用这些方法。用户可以更改方法类型(加、减、...),因此我想创建一个方法指针数组(method_pointer),其中通过选择整数“method_type”来选择方法。我有一个 C 版本,其中所有内容都在一个文件中,而不是类的成员,这可以正常工作;但是,当指针是类的成员时,我会收到“Method_pointer 不是函数或函数指针”错误。我无法获得正确的语法,任何帮助将不胜感激。下面是我正在尝试做的示例程序。
Method.h 头文件
class Method{
public:
Method();
~Method();
void add(int, int, int);
void subtract(int, int, int);
void multiply(int, int, int);
void divide(int, int, int);
void DoMath(int, int, int);
void set_method( const int method_number);
private:
int method_type;
};
Run Code Online (Sandbox Code Playgroud)
Method.cc 来源
#include "method.h"
typedef void (*method_function)(int, int,int);
Method::Method(){
method_type=2;
}
Method::~Method(){
}
void Method::set_method( int method_number){
method_type=method_number;
}
void Method::add( int a, int b, int c){
c=a+b;
}
void Method::subtract( int a, int b, int c){
c=a+b;
}
void Method::multiply( int a, int b, int c){
c=a+b;
}
void Method::divide( int a, int b, int c){
c=a+b;
}
void Method::DoMath(int x, int y, int result){
method_function method_pointer[4]={add,subtract, multiply,divide};
result=method_pointer[method_type](x,y);
}
Run Code Online (Sandbox Code Playgroud)
主文件
int main(int argc, const char * argv[]) {
Method *method;
int x=2;
int y=3;
int result=0;
Method.DoMath(x,y,result);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
指向方法的指针与指向函数的指针略有不同。所以,要声明一个,你会写:
typedef void (Method::*method_function)(int, int,int);
Run Code Online (Sandbox Code Playgroud)
并且你必须指定一个对象来调用这个方法:
method_function method_pointer[4] = {&Method::add, &Method::subtract, &Method::multiply, &Method::divide};
method_function func = method_pointer[method_type];
result = (this->*func)(x,y);
Run Code Online (Sandbox Code Playgroud)
但是,如果您要进行设计,请不要忘记将函数的第三个参数作为参考。否则,您将无法提取结果。因此,正确的 typedef 将是:
typedef void (Method::*method_function)(int, int,int&);
Run Code Online (Sandbox Code Playgroud)
并且您必须相应地更改您的方法签名。
最后,为什么在主函数中使用指针?您可能应该使用堆栈变量(或至少初始化指针),如果这样做,您需要在对象而不是类上调用 DoMath:
Method method;
// ...
method.DoMath(x, y, result);
Run Code Online (Sandbox Code Playgroud)