0

我有以下代码

#include<iostream>
using namespace std;
class operate
{
    int x;
    int y;
public:
    operate(int _x, int _y):x(_x), y(_y)
    {}
    void add(const char* ch)
    {
        cout<<ch<<" "<<x+y;
    }
    void subtract(const char* ch)
    {
        cout<<ch<<" "<<x-y;
    }
    void multiply(const char* ch)
    {
        cout<<ch<<" "<<x*y;
    }
};
int main()
{
    void (operate::*fptr[3])(const char*);
    operate obj(2,3);
    fptr[0] = &(operate.add);              //problem
    fptr[1] = &(operate.multiply);         //problem
    fptr[2] = &(operate.subtract);         //problem
    (obj.*fptr[0])("adding");
    (obj.*fptr[1])("multiplying");
    (obj.*fptr[2])("subtracting");
}

看来我没有正确地将成员函数分配给函数指针数组。我该如何解决这个问题。我正在使用 VS2010

4

2 回答 2

4

点(成员)运算符用于访问对象的成员。对于类和命名空间,您必须使用::运算符。另外,不要加括号,因为它的&优先级比::它低,而且更易读

fptr[0] = &operate::add;
于 2013-07-16T08:44:45.577 回答
0

这应该做的工作

void testFP()
{
    typedef void (operate::*memFP)(const char*); 
    memFP fptr[3];

    fptr[0] = &operate::add;
    fptr[1] = &operate::multiply;
    fptr[2] = &operate::subtract;
    operate op(42, 42);

    (op.*(fptr[0]))("adding");
}
于 2013-07-16T09:04:40.797 回答