gpt4 book ai didi

c++ - 无法访问派生类中的基类方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:05:28 25 4
gpt4 key购买 nike

我有一个基如下:

template<typename aGamePieceBase> class GamePiece : public aGamePieceBase
{
public:
// Each GamePiece contains a definition of the base class from which it was derived
typedef aGamePieceBase gamePieceBase

// Returns this piece's sprite
virtual sf::Sprite* getSprite()
{
return m_pSprite;
}
protected:
sf::Sprite* m_pSprite;
}

还有一个派生的:

class Horse : public GameBoard::GamePiece< GameBoard::GamePieceBase >
{
public:
virtual sf::Sprite* getSprite() override
{
// Do stuff
}
};

但是我在 Horse::getSprite 减速时遇到了这个错误用 override 声明的成员函数不会覆盖基类成员

为什么 getSprite 在 Horse 中不可用?

GamePieceBase 如下:

class GamePieceBase : public GameEventHandler
{
public:
// Called when the GamePiece has been added to the GameBoard
template<typename aTileBase> virtual void onPieceCreate( Tile<aTileBase> *startingLocation ){}
// Called when the GamePiece has been removed from the GameBoard
virtual void onPieceRemove(){}
// Called when the user has selected this GamePiece
virtual void onPieceSelect(){}
// Called when the user has de-selected this GamePiece
virtual void onPieceDeselect(){}
// Called when this GamePiece has moved on the board
template<typename originTileBase, typename destinationTileBase> virtual void onPieceMove( Tile<originTileBase>* originTileBase, Tile<destinationTileBase>* pDestinationTile ){}
};

编辑:输出日志表明有一个内部编译器 error 但没有提供很多细节。我现在正在调查这个

最佳答案

这对我有用:

class GamePieceBase
{
public:
// Called when the GamePiece has been added to the GameBoard
};


template<typename aGamePieceBase> class GamePiece : public aGamePieceBase
{
public:
// Each GamePiece contains a definition of the base class from which it was derived
// typedef aGamePieceBase gamePieceBase

// Returns this piece's sprite
virtual int getSprite()
{
return 0;
}
protected:

};


class Horse : public GamePiece< GamePieceBase >
{
public:
virtual int getSprite() override
{
return 0;
}
};

但是,最好这样写:

int getSprite() override

显式编写 virtualoverridefinal 是 self 记录的,使编译器能够捕获类型和/或名称之间的不匹配基类和派生类。但是,编写这三者中的一个以上既是多余的,也是潜在的错误来源。 C++ CoreGuidelines C.128

关于c++ - 无法访问派生类中的基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com