关于类成员函数指针的问题。在线等。
我的程序:
#include "stdafx.h"
using namespace std;
class A
{
public:
int index;
void update(int i)
{
cout<<index<<" "<<i<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
typedef void (A::*FUNC)(int i);
FUNC func = &A::update;
A a;
a.*func(1);//有问题的行
system("pause");
return 0;
}
为何编译器提示:error C2064: 项不会计算为接受 1 个参数的函数。
问题点数:20、回复次数:7Top
1 楼wanamaker()回复于 2004-08-03 14:46:51 得分 16
a.*func(1);//有问题的行
--->
(a.*func)(1);
Top
2 楼lingjingqiu(空明流转)回复于 2004-08-03 14:48:50 得分 0
好眼力!Top
3 楼geesun(还是Geesun!)回复于 2004-08-03 14:53:08 得分 1
class A
{
public:
static int index;//must be static ,may be can not use in static func
static void update(int i) //must be the static,if is not, it can not get the addr
{
cout<<index<<" "<<i<<endl;
}
};
int A::index=0;
int main()
{
typedef void (*FUNC)(int i);
FUNC func = &(A::update);// A::update's type likes void fun(int i)
A a;
(*func)(1);
//a.func(1);
//system("pause");
return 0;
}Top
4 楼lwj_dxy(豆芽--抵制日货)回复于 2004-08-03 14:59:25 得分 1
upTop
5 楼darkstar21cn(≮天残≯无畏)(死亡进行时)回复于 2004-08-03 15:02:28 得分 1
typedef void (A::*FUNC)(int i);
这个错了,这么定义是指FUNC是属于类A的,而你这明显不是
FUNC func = &A::update;
update 在A没有实例化之前使用,出问题了,如果你想这么用,最好把它声明为static的
cout<<index<<" "<<i<<endl;
如果update改为static后,在这是无法使用index了,除非index也是static
a.*func(1);
func这并不是a的成员,虽然它是指向a成员的指针。
修改后的:
#include "stdafx.h"
using namespace std;
class A
{
public:
int index;
static void update(int i);
};
void A::update(int i)
{
cout<<" "<<i<<endl;
};
int _tmain(int argc, _TCHAR* argv[])
{
typedef void (*FUNC)(int);
FUNC func = &(A::update);
A a;
func(1);//有问题的行
system("pause");
return 0;
}Top
6 楼lingjingqiu(空明流转)回复于 2004-08-03 15:46:54 得分 0
楼上的,类和函数的偏移关系在编译期就确定了。所以,不管在什么地方,只要没有访问限制的话都可以使用&A::update。还是1楼的正确。一眼就看出问题所在。Top
7 楼langzi8818(┤天道酬勤┝爱老婆┦┷我是来学习滴┷)回复于 2004-08-03 18:13:41 得分 1
PFPF~~Top




