〓〓〓 哪里出错?类的指针问题!问题解决,马上结贴! 〓〓〓
class Player
{
public:
inline int play();
int abc;
private:
int i;
};
inline int Player::play()
{
return i = 30;
}
int main(int argc, char* argv[])
{
typedef Player& (Player::*p)();
p def = &Player::play; //此行出错!
return 0;
}
====================================
Compiling...
test.cpp
C:\Documents and Settings\Administrator\桌面\test\test.cpp(29) : error C2440: 'initializing' : cannot convert from 'int (__thiscall Player::*)(void)' to 'class Player &(__thiscall Player::*)(void)'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
Error executing cl.exe.
test.exe - 1 error(s), 0 warning(s)
问题点数:20、回复次数:12Top
1 楼wanamaker()回复于 2004-08-03 10:06:36 得分 8
typedef Player& (Player::*p)();
---〉
typedef int (Player::*p)();Top
2 楼bgu(彼岸)回复于 2004-08-03 10:11:52 得分 0
???
改成:
typedef int (Player::*p)();
就可以了!
--------------
怎么,《C++ primer》写错了???535页!
楼上的可以解析下不?Top
3 楼wanamaker()回复于 2004-08-03 10:17:49 得分 0
&play的类型是int (Player::*)(),
def的类型要跟它一致Top
4 楼lemon520(喷血)回复于 2004-08-03 10:19:52 得分 2
函数原型是int Player::play();
显然应该typedef int (Player::*)();
不然就类型不匹配了
Lippman 的书有好多小错误的Top
5 楼yuanye2008(yuanye218)回复于 2004-08-03 10:28:51 得分 0
可不可以说的详细一点:
typedef Player& (Player::*p)();
or
typedef int (Player::*)();
是什么意思?
p def = &Player::play; 又如何理解?Top
6 楼lemon520(喷血)回复于 2004-08-03 10:35:21 得分 5
typedef int (Player::*P)();
表示声明(注意:是声明类型)了一个指针类型,类型名为P;当然你也可以取其他名字
P指向的函数类型为:返回int 、是Player的成员函数、没有参数;
P def=&Player::play; //表示用P定义了一个指针def,并用Player::play的地址初始化它
如果是普通函数(不是成员函数),如 int* fun(int* a);
则可以向这样声明一个指向该函数的指针
typedef int* (*P) (int*);
Top
7 楼wanamaker()回复于 2004-08-03 10:38:46 得分 0
typedef 是类型定义亚,比如说:
int* pInt;// pInt 是个int指针
typedef int* pInt;// pInt是int指针数据类型,pInt p; p就是个int指针。
Top
8 楼yuanye2008(yuanye218)回复于 2004-08-03 10:41:55 得分 0
谢谢 lemon520(喷血)的回复!说得很详细、清楚。
Top
9 楼allen1981813(Nahe des Geliebten)回复于 2004-08-03 10:42:31 得分 2
class Player
{
public:
int play();
int abc;
private:
int i;
};
int Player::play()
{
return i = 30;
}
int main()
{
typedef int ( Player::*p )();
p def = Player::play;
return 0;
}Top
10 楼geesun(还是Geesun!)回复于 2004-08-03 10:53:20 得分 3
按照上面改了还应该会有错误!
不妨这样!
#include<iostream>
using namespace std;
typedef int (*Func)();
class Player
{
public:
static inline int play(); //只有静态函数才能取地址吧!
int abc;
private:
static int i;
};
int Player::i =0;
inline int Player::play()
{
return i = 30;
}
int main(int argc, char* argv[])
{
typedef int (Player::*p)();
//p def = &(Player::play); //&(Player::play)的类型是 int func()
typedef int (*p1)();
p1 def2 = &(Player::play); //这样才正确!
}
我是在gcc下面编译能通过!Top
11 楼kaphoon(齐柏林飞艇)回复于 2004-08-03 11:13:26 得分 0
楼上正解
p1 def2 = &(Player::play); //这样才正确!
总觉得这个&,显得画蛇添足的味道~
Top
12 楼baconbally(一屋不扫睡大觉)回复于 2004-08-03 14:21:00 得分 0
p1 def2 = &(Player::play); //这样才正确!
总觉得这个&,显得画蛇添足的味道~
-------------------------------------------------------
可以不要这个&,要了也可以Top




