且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指向成员函数的函数指针

更新时间:2021-11-16 05:29:59

语法错误.成员指针是与普通指针不同的类型类别.成员指针必须与其类的对象一起使用:

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.