关于我的游戏中的继承的问题
我有一个从 Humanoid 派生的 Player 类,而 Humanoid 又从 Sprite 派生,到目前为止
Sprite -> Humanoid -> Player
一切都很好。 Sprite 具有 virtual 方法
virtual sf::Sprite getSprite() { return sprite_; }
,其中 sprite 是可以绘制到屏幕上的图像对象。
Humanoid 声明virtual sf::Sprite getSprite();
Player 定义virtual sf::Sprite getSprite() { return sprite_; } }
Sprite 有一个成员 sprite_
;这就是我想要做的:
1)创建一个玩家类,同时传递一个精灵,如下所示
Player::Player(sf::Image image)
: Humanoid()
{
sprite_.SetImage(image); // Converts sf::Image to sf::Sprite
}
2)从我的游戏类将其绘制在屏幕上,如下
sf::Image playerImage;
if(!playerImage.LoadFromFile("Link/Link.png"))
std::cin.get();
Player *player = new Player(playerImage);
/* ... */
App.Draw(player->GetSprite());
测试程序,我发现 player->getSprite ()
方法确实被调用,但我担心我可能隐藏了 Sprite::getSprite()
方法,而不是实际派生和使用它。由于 Sprite 类有一个受保护的 sprite_ 成员,因此当我调用该函数时,我对实际返回哪个 sprite_ 对象感到困惑。
另外,图像文件似乎在某处丢失了,在 SFML 论坛上发帖之前,我想确认一下我的继承树是否实际上正确。
I have a Player class that derives from Humanoid and Humanoid derives from Sprite like so
Sprite -> Humanoid -> Player
So far so good. Sprite has the virtual method
virtual sf::Sprite getSprite() { return sprite_; }
where sprite is an image object that can be drawn onto the screen.
Humanoid declares virtual sf::Sprite getSprite();
Player defines virtual sf::Sprite getSprite() { return sprite_; }
Sprite has a member sprite_
; this is what I want to do:
1) Create a player class while passing a sprite like so
Player::Player(sf::Image image)
: Humanoid()
{
sprite_.SetImage(image); // Converts sf::Image to sf::Sprite
}
2) Drawing it on the screen from my Game class like so
sf::Image playerImage;
if(!playerImage.LoadFromFile("Link/Link.png"))
std::cin.get();
Player *player = new Player(playerImage);
/* ... */
App.Draw(player->GetSprite());
Testing the program, I have found that the player->getSprite()
method is indeed called, but I fear that I may have hidden the Sprite::getSprite()
method instead of actually deriving and using it. Since the Sprite class has a protected sprite_ member, I'm confused as to which sprite_ object I'm actually returning when I call the function.
Also, it seems like the image file got lost somewhere along the line, and before I post in the SFML forum I would like some confirmation as to whether or not my inheritance tree is actually correct or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
Sprite
类具有sprite_
成员,并且没有派生类 (Humanoid/Player
) 添加同名成员,则有每个实例只有一个sprite_
对象,并且该函数应该按预期工作。我不明白为什么你要覆盖getSprite
如果你给它完全相同的行为。If the
Sprite
class has asprite_
member and none of the derived classes (Humanoid/Player
) have added a member with the same name then there is only onesprite_
object for each instance and the function should work as expected. I don't understand why you're overridinggetSprite
if you give it the exact same behaviour though.