指向成员函数指针调用的问题

ssdx 2010-01-19 04:21:09

#include <iostream>
#include <cstdio>

class CTest
{
public:
int fun1(int i)
{
std::cout << "fun1" << std::endl;
return 0;
}

int fun2(int i)
{
std::cout << "fun2" << std::endl;
return 0;
}

void testPfun(void)
{
int (CTest::*pFun)(int) = &CTest::fun1;
pFun(1); ------ error C2064: term does not evaluate to a function taking 1 arguments
(int(CTest::*)(int))pFun(1); ----- error C2064: term does not evaluate to a function taking 1 arguments
}
};

int main(int argc, char *argv)
{
CTest o1;
o1.testPfun();

system("pause");
}


两个调用位置都包无法将pFun解释为函数指针调用,想问一下该怎么写通过pFun调用fun1/fun2?
...全文
227 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
linuhuge 2010-01-20
  • 打赏
  • 举报
回复
.*
->*

专为成员函数指针准备的
macrojj 2010-01-19
  • 打赏
  • 举报
回复
JF
ssdx 2010-01-19
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 hairetz 的回复:]
typedef int (*Fun)(int);
Fun pFun=&CTest::fun1;
即可。
[/Quote]
我问的怎么调用,不是怎么定义。
而且typedef起个别名而已,采用原帖里面的调用方式也是错的。


1楼我自己回答了,用.* ->*这两个操作符。

c++ primer 4th edtion:
18.3.2. Using a Pointer to Class Member
Analogous to the member access operators, operators. and ->, are two new operators, .* and .->, that let us bind a pointer to member to an actual object. The left-hand operand of these operators must be an object of or pointer to the class type, respectively. The right-hand operand is a pointer to a member of that type:

The pointer-to-member dereference operator (.*) fetches the member from an object or reference.

The pointer-to-member arrow operator (->*) fetches the member through a pointer to an object.
traceless 2010-01-19
  • 打赏
  • 举报
回复
LZ 你改了后是对的,相信自己
ssdx 2010-01-19
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 leewon1988 的回复:]
你函数指针定义不对啊
定义成 int(CTest::*pf)(int)
[/Quote]

是吗?
  • 打赏
  • 举报
回复

typedef int (*Fun)(int);
Fun pFun=&CTest::fun1;
即可。
cattycat 2010-01-19
  • 打赏
  • 举报
回复
前面加this就行。
leewon1988 2010-01-19
  • 打赏
  • 举报
回复
你函数指针定义不对啊
定义成 int(CTest::*pf)(int)
stardust20 2010-01-19
  • 打赏
  • 举报
回复
jf
traceless 2010-01-19
  • 打赏
  • 举报
回复
还是建议你这样:

public:
typedef int (CTest::*pFun)(int );

然后使用:
pFun pfoo1 = &CTest::fun1;
(this->*pfoo1)(1);
tan870426 2010-01-19
  • 打赏
  • 举报
回复
pengzhixi 2010-01-19
  • 打赏
  • 举报
回复
jf
ssdx 2010-01-19
  • 打赏
  • 举报
回复
自己搞定
(this->*pFun)(1);

.*
->*
用这两个操作符

65,189

社区成员

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

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