我想将一个函数指针设置为一个类的成员,该类是指向同一类中另一个函数的指针。我这样做的原因很复杂。
在此示例中,我希望输出为“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/63326217/