我想将函数指针设置为一个类的成员,它是指向同一类中另一个函数的指针。我这样做的原因很复杂。
在本例中,我希望输出为“1”
class A {
public:
int f();
int (*x)();
}
int A::f() {
return 1;
}
int main() {
A a;
a.x = a.f;
printf("%d\n",a.x())
}
但这在编译时失败。为什么?
最佳答案
语法错误。成员指针是与普通指针不同的类型类别。成员指针必须与其类的对象一起使用:
class A {
public:
int f();
int (A::*x)(); // <- declare by saying what class it is a pointer to
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f; // use the :: syntax
printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}
a.x
还没有说明要调用函数的对象。它只是说你想使用存储在对象 a
中的指针。再次将 a
作为左操作数添加到 .*
运算符将告诉编译器在哪个对象上调用该函数。
关于c++ - 指向成员函数的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2402579/