【发布时间】:2012-05-04 19:01:14
【问题描述】:
#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
上面的代码在 A 类中有一个 B 类,A 类有一个方法 taunt,它接受一个函数作为参数。 B 类的 getMsg 被传递到 taunt...上面的代码生成了以下错误消息:“error: no matching function for call to 'A::taunt()'”
是什么导致了上述代码中的错误消息?我错过了什么吗?
更新:
#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (B::*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
t.cpp:在成员函数 'void A::run()' 中: 第 19 行:错误:没有用于调用 'A::taunt()' 的匹配函数 编译因 -Wfatal-errors 而终止。
将 (*msg)(int) 更改为 (B::*msg)(int) 后,我仍然遇到同样的错误
【问题讨论】:
-
你不能像在 C++ 中那样使用成员函数指针。试着用谷歌搜索一下,那里有很多关于它的文章。
-
在一个地方你传递了一个
int,而在另一个地方,你传递了一个int(B::*)(int),而在另一个地方,你传递了一个int(*)(int);你为什么期望这行得通? -
我刚刚注意到...并且我刚刚修复了它
标签: c++ function-pointers