关于类成员函数中函数指针参数的问题!!

jianlirong 2005-10-30 12:58:56
请各位看看,以下代码为啥没法通过编译?

#include <iostream>
#include <math.h>

using namespace std;

class BaseA
{
public:
BaseA()
{
data=0;
}

BaseA(int num)
{
data=num;
}

int Done(int(*Fun)(int))
{
return Fun(data);
}

int Test(int num)
{
return (int)sqrt(num);
}

int DDone()
{
return Done(Test);
}

private:
int data;
};

int main()
{
BaseA First(8);
cout<<First.DDone()<<endl;

return 0;
}

报错是:

--------------------Configuration: grade_twoproject - Win32 Debug--------------------
Compiling...
27.cpp
C:\Program Files\Microsoft Visual Studio\MyProjects\grade_twoproject\27.cpp(31) : error C2664: 'Done' : cannot convert parameter 1 from 'int (int)' to 'int (__cdecl *)(int)'
None of the functions with this name in scope match the target type
执行 cl.exe 时出错.

27.obj - 1 error(s), 0 warning(s)

谢谢了!!
...全文
397 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wzjall 2005-10-30
  • 打赏
  • 举报
回复
类函数指针必须要加类限定符,楼上的才是正确的做法.
B_S 2005-10-30
  • 打赏
  • 举报
回复
关注ing...找人来解释一吓吧...不懂..
wanguodu 2005-10-30
  • 打赏
  • 举报
回复
class BaseA
{
...

int Done(int (BaseA::*f)(int))
{
return (this->*f)(data);
}

...
}
languagec 2005-10-30
  • 打赏
  • 举报
回复
cxyol 2005-10-30
  • 打赏
  • 举报
回复
http://dev.csdn.net/develop/article/25/25143.shtm
fiftymetre 2005-10-30
  • 打赏
  • 举报
回复
没必要用函数指针的,类函数指针的调用方式和普通函数指针不太一样
如果真要这么用,你可是试一下用typedef声明的

typedef int(thiscall BaseA::*func)(int);
然后用func作为函数指针类型试一下

我这里没有vc没办法调试的..
ericqxg007 2005-10-30
  • 打赏
  • 举报
回复
用函数指针传递类里面的其他方法 这样的做法不行(既然要调用Test方法 你还不如直接在DDone中直接调用Test就行了 没有必要用函数指针)
ywfscu 2005-10-30
  • 打赏
  • 举报
回复
普通函数,不是普通成员
ywfscu 2005-10-30
  • 打赏
  • 举报
回复
类的成员函数的编译模式和普通成员的编译模式不一样,
一个是thiscall,一个是__cdecl

64,641

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧