【问题标题】:Beginner trying to learn inheritance with game programming初学者尝试通过游戏编程学习继承
【发布时间】:2015-09-15 14:59:27
【问题描述】:

我正在尝试为我正在制作的 SFML 游戏制作一个框架,但我遇到了继承问题。我以为我知道该怎么做,但似乎不对。我希望我的 main 基本上只调用 GameLoop ,仅此而已。在我的 GameLoop 类中,我有制作窗口和运行游戏的方法。然后我希望我的 GamePlayScreen 类实际处理游戏逻辑,但由于某种原因,我无法弄清楚如何从 GameLoop 继承。我正在观看一段视频,而那个人正在使用 C#,这就是我无法转换它的原因。视频是https://www.youtube.com/watch?v=WhbeqOOSDEo&index=2&list=PLfTDIoEcaNroztBVGPA0aU3NbOauRVIe3

GameLoop.h

#pragma once
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <string>

class GameLoop
{
public:
    GameLoop(int width, int height, std::string title);
    virtual void Run();
    virtual void LoadContent();
    virtual void Initialize();
    virtual void Update();
    virtual void Render();

    sf::RenderWindow window;
};

GameLoop.cpp

#include "GameLoop.h"


GameLoop::GameLoop(int width, int height, std::string title)
{
    window = sf::RenderWindow(sf::VideoMode(width, height), title, sf::Style::Default);
}


void GameLoop::Run()
{
    LoadContent();
    Initialize();

    while (window.isOpen())
    {
        sf::Event event;

        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        Update();
        window.clear();
        Render();
        window.display();
    }
}

void GameLoop::LoadContent()
{

}

void GameLoop::Initialize()
{

}

void GameLoop::Update()
{

}

void GameLoop::Render()
{

}

GamePlayScreen.h

#pragma once
#include "GameLoop.h"
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>

class GamePlayScreen : public GameLoop
{
public:
    GamePlayScreen();
    void Initialize();

};

GamePlayScreen.cpp

#include "GamePlayScreen.h"

GamePlayScreen::GameLoop(800, 600, "Game");
{

}

void GamePlayScreen::Initialize()
{
    GameLoop game(800, 600, "Game");
}

【问题讨论】:

  • 有什么问题吗?你得到一个编译器错误吗?运行时错误?
  • 阅读How to Ask,然后将那里的指南与您的问题进行比较。
  • 我只是不知道该怎么做。我在 GamePlayScreen 中搞砸了,但真的不知道如何调用方法或构造函数。
  • 首先,GamePlayScreen 继承自 GameLoop 似乎很奇怪。这没有意义,因为屏幕不是循环。 GamePlayScreen::GameLoop(800, 600, "Game");{}
  • 继承是一种“is-a”关系。例如,龙“是”怪物,因此可能的 Dragon 类继承自可能的 Monster 类是有意义的。您还需要了解inheritancecomposition 之间的区别,以及何时使用其中一个。

标签: c++ inheritance sfml


【解决方案1】:

当您“新建”类时,将自动调用构造函数。只需在 GamePlayScreen 中创建匹配的构造函数,系统将首先调用派生构造函数 - 但签名必须匹配。

class GamePlayScreen : public GameLoop
{
public:
    GamePlayScreen();
    GamePlayScreen(int width, int height, std::string title);
    void Initialize();

};

【讨论】:

    【解决方案2】:

    也许这不是一个真正的答案,但我无法发表评论。 正如我所看到的,主要主题是关于“处理多个屏幕”。 所以你可以看看这个教程:https://github.com/SFML/SFML/wiki/Tutorial:-Manage-different-Screens

    【讨论】:

      猜你喜欢
      • 2023-02-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多