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

标签 c++ oop function-pointers

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

在本例中,我希望输出为“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/2402579/

相关文章:

iphone - 识别 'if statement' 中的按钮按下

c# - 属性 Get v 方法的性能

c++ - 交叉编译器/平台裸包装函数,无条件跳转到函数指针

c++ - 递归中的运行时内存错误用c++中的字符函数替换空格

c++ - Qt 生成文件错误

c++ - 将数字乘以矩阵

c++ - 在 cout << "hello"<< endl 中删除 endl 后,我的 C++ 程序停止工作

oop - 如何正确使用状态模式?

c++ - 如何将指针传递给模板类的成员函数?

C++:通用函数包装类作为非模板类​​的成员