我有以下代码
#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
答案 0 :(得分:4)
dot(member-of)运算符用于访问对象的成员。对于类和名称空间,您必须使用::
运算符。另外,请勿使用括号,因为&
的优先级低于::
,而且它的可读性更高
fptr[0] = &operate::add;
答案 1 :(得分: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");
}