成员函数指针问题?

joyself 2005-07-04 09:24:35
代人问的。
下面的代码:

class base
{
public:
static int getf(int (base::** pfun)( int a, int b));
};


class class1 : public base
{
public:
int add( int a, int b){
return a + b;
}
};

class class2 : public base
{
public:
int sub(int a, int b){
return a - b;
}
};

int main()
{
int (base::*const pfa[])(int a, int b) = {
(int (base::*)(int, int)) class1::add,
(int (base::*)(int, int)) class2::sub
};


//int addition = (*pfa[0])(1, 3);
//int subt = (*pfa[1])(3, 1);
return 0;
}
错误信息:
cpplus.cpp:27: cannot convert `class1::add(int, int)' from type `int (*)(int,
int)' to type `int (base::*)(int, int)'
cpplus.cpp:29: cannot convert `class2::sub(int, int)' from type `int (*)(int,
int)' to type `int (base::*)(int, int)'

...全文
211 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
waynahu 2005-07-06
  • 打赏
  • 举报
回复
mark
xjp6688 2005-07-06
  • 打赏
  • 举报
回复
弄这么复杂做什么?
meteor135 2005-07-06
  • 打赏
  • 举报
回复
不通过类的对象怎么能够调用类的非静态函数?
//int addition = (*pfa[0])(1, 3);
//int subt = (*pfa[1])(3, 1);
foochow 2005-07-05
  • 打赏
  • 举报
回复
//int addition = (*pfa[0])(1, 3);
//int subt = (*pfa[1])(3, 1);
能这样用吗??
foochow 2005-07-05
  • 打赏
  • 举报
回复
VC6.0编译没有问题,运行正常
cenlmmx 2005-07-05
  • 打赏
  • 举报
回复
class base
{
public:
static int getf(int (base::** pfun)( int a, int b)); //没什么用
};
其他楼上的说的差不多了
西门豆豆 2005-07-04
  • 打赏
  • 举报
回复
对于
int (base::*const pfa[])(int a, int b) = {
(int (base::*)(int, int)) class1::add,
(int (base::*)(int, int)) class2::sub
};

有些老的编译器可以通过没有&号的赋值方式,但标准C++强制要求加上&号,
所以,我估计你这样改可能就没问题了:
int (base::*const pfa[])(int a, int b) = {
(int (base::*)(int, int)) &class1::add,
(int (base::*)(int, int)) &class2::sub
};
西门豆豆 2005-07-04
  • 打赏
  • 举报
回复
终于弄明白了,
int (base::*const pfa[])(int a, int b)
这个函数指针数组的声明是声明了base类的一个成员,你使用它的时候必须用base对象或者对象指针去调用它,注释掉的那两句譬如这样改就对了:
base abc;
int addition = (abc.*pfa[0])(1, 3);
int subt = (abc.*pfa[1])(3, 1);
西门豆豆 2005-07-04
  • 打赏
  • 举报
回复
你上面的程序没有问题,只不过下面的2个注释掉的语句放开却无法通过,百思不得其解。

64,654

社区成员

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

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