c++ - 指向成员函数的函数指针

标签 c++ oop function-pointers pointer-to-member member-functions

我想设置一个函数指针作为类的成员,该类是指向同一类中另一个函数的指针。我这样做的原因很复杂。

在这个例子中,我希望输出为“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/59412578/

相关文章:

c++ - 如果嵌套对象具有相同的地址,编译器如何区分它们?

c - 如何使用函数指针执行算术运算?

Python:如何创建带有设置参数的函数指针?

c - 在 C 中将 func(const void *) 赋值给 func(void *)

c++ - 我将如何从二叉树写入 txt 文件?

c++ - recv() 失败 : Bad file descriptor c++ Linux

C++类指针成员行为奇怪(错误)

Java 问题 : Is it a method?

java - 使用上述方法进行面向对象编程。 java

oop - 封装: allow accessing of fields of any other than the current receiver object