C ++返回类型与函数类型不匹配

时间:2012-05-20 17:10:33

标签: c++

当我尝试在我的函数中返回指向播放器的指针时,我收到错误'返回类型与函数类型不匹配'。编译器的错误是:

  

'&安培;' :对绑定成员函数表达式的非法操作

CPlayer* CLevel::getPlayer()
{
return &player;
}

在头文件中,定义为:

private:
    CPlayer player(Point p, CGame* game);

public:
    CPlayer* getPlayer();

关于我为什么会收到此错误以及如何删除错误的任何想法?

编辑:

关卡构造函数:

CLevel::CLevel()
{
Point p;
this->game=game;
p.x=0;
p.y=0;
player(Point p, CGame* game) {};

memset(tiles, GROUND, sizeof(TileType)*GRID_HEIGHT*GRID_WIDTH);
}

Player.cpp构造函数:

 CPlayer::CPlayer(Point pos, CGame* game)
 {
this->game=game;
Point p;
p.x=0;
p.y=0;
setPosition(p);
 }

1 个答案:

答案 0 :(得分:3)

因为在您的代码中,player是私有函数的名称:

private:
    CPlayer player(Point p, CGame* game);

此功能需要PointCGame*,并返回CPlayer

宣布您需要的CPlayer数据成员

private:
    CPlayer player;

然后可以在构造函数中初始化,例如:

CLevel(Point p, CGame* game) : player(p, game) {}

CLevel() : player(Point(), game) {
  this->game = .... ;
}

或者,在C ++ 11中,你可以这样做:

private:
    CPlayer player{Point(), nullptr}; // I am not sure where you were getting p and game in your original example