c++ - 在类中使用成员函数指针

标签 c++ pointer-to-member

给定一个示例类:

class Fred
{
public:
Fred() 
{
    func = &Fred::fa;
}

void run()
{
     int foo, bar;
     *func(foo,bar);
}

double fa(int x, int y);
double fb(int x, int y);

private:
double (Fred::*func)(int x, int y);
};

我在通过指针“*func(foo,bar)”调用成员函数的那一行遇到编译器错误,说:“term does not evaluate to a function taking 2 arguments”。我做错了什么?

最佳答案

你需要的语法如下:

((object).*(ptrToMember)) 

所以你的电话是:

((*this).*(func))(foo, bar);

我相信另一种语法是:

(this->*func)(foo, bar);

关于c++ - 在类中使用成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2898316/

相关文章:

c++ - Services.msc 中未显示 ATL 服务

c++ - 通过循环 std::map 调用类方法

c++ - 如何在 C++ 中打印成员函数地址

c++ - 错误 : expected primary-expression before X token

c++ - 链接到动态库的静态库中的 undefined symbol

使用成员函数作为模板参数时的c++编译错误

c++ - 将成员函数指针转换为 TIMERPROC

c++ - 将成员函数指针传递给无类函数

c++ - 编译器发出 std::move() 运行时调用?

c++ - 删除其中的一个元素时出现段错误