成员函数的函数指针 [英] 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\n",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\n",(a.*(a.x))()); // use together with an object of its class
}
ax
还没有说明该函数要调用的对象。它只是说你想使用存储在对象 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屋!