指向成员函数的函数指针 [英] Function pointer to member function
问题描述
我想将函数指针设置为类的成员,该类是指向同一类中另一个函数的指针.我这样做的原因很复杂.
I'd like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I'm doing this are complicated.
在这个例子中,我希望输出为1"
In this example, I would like the output to be "1"
class A {
public:
int f();
int (*x)();
}
int A::f() {
return 1;
}
int main() {
A a;
a.x = a.f;
printf("%d
",a.x())
}
但这在编译时失败.为什么?
But this fails at compiling. Why?
推荐答案
语法错误.成员指针是与普通指针不同的类型类别.成员指针必须与其类的对象一起使用:
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:
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
",(a.*(a.x))()); // use together with an object of its class
}
a.x
还没有说明要调用函数的对象.它只是说你想使用存储在对象a
中的指针.再次将 a
作为左操作数添加到 .*
运算符将告诉编译器在哪个对象上调用函数.
a.x
does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a
. Prepending a
another time as the left operand to the .*
operator will tell the compiler on what object to call the function on.
这篇关于指向成员函数的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!