0
class Game {
  private:
    string title;
    bool running;
    State currentState;

  public:
    sf::RenderWindow window;
    void setup();
    void run();
};

我有一个名为 currentState 的变量。这是状态:

#ifndef STATE_HPP
#define STATE_HPP

using namespace std;

class State {
  private:

  public:
    void start();
    void update();
    void render();
};

#endif

然后我有一个名为 PlayState 的类,它继承了 State:

#ifndef PLAY_STATE_HPP
#define PLAY_STATE_HPP

#include <SFML/Graphics.hpp>

#include "Game.hpp"
#include "State.hpp"

using namespace std;

class PlayState : public State {
  private:
    sf::CircleShape shape;
    Game game;

  public:
    PlayState();
    void start();
    void update();
    void render();
};

#endif

在我的 Game.cpp 上,我正在创建 currentState,方法是:

currentState = PlayState();

但是,问题是它不起作用。currentState.update() 是 state.update()。创建 PlayState 时,我似乎没有覆盖 State 方法

这是 PlayState.cpp:

#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <stdio.h>

#include "PlayState.hpp"

PlayState::PlayState() {
  printf("heyyy\n");
}

void PlayState::start() {
  shape.setRadius(100.f);
  shape.setOrigin(20.0f, 20.0f);
  shape.setFillColor(sf::Color::Green);
}

void PlayState::update() {
  sf::Event event;
  while (game.window.pollEvent(event)) {
    if (event.type == sf::Event::Closed) {
      game.window.close();
      //running = false;
    }
  }

  printf("here\n");
}

void PlayState::render() {
  printf("here\n");
  game.window.clear();
  game.window.draw(shape);
  game.window.display();
}

关于如何“覆盖”这些方法的任何想法?谢谢你。

编辑 我必须使 State.cpp 函数成为虚拟函数,以便它们可以被覆盖。我还必须将 State *currentState 定义为指针并使用“currentState = new PlayState();”创建 PlayState。另外,现在我使用 ->update() 和 ->draw() 访问 .update 和 .draw。

4

3 回答 3

3

Two problems. As @McAden said, the functions in State that are to be overridden in PlayState need to be marked virtual. The other problem is that the data member currentState in Game has type State. When you assign an object of type PlayState to it, it gets the State part of the PlayState object, but not the derived parts. This is called "slicing". To prevent it, make currentState a pointer to State, and when you create that PlayState object, assign its address to the Game object's currentState.

于 2012-08-29T21:39:23.647 回答
1

您正在寻找的是虚函数的概念。

维基百科条目

国家需求:

virtual void update();

PlayState 需要:

void update();
于 2012-08-29T21:32:25.000 回答
1

您需要使用虚拟修饰符来制作您的函数,即。

virtual void Update();

当调用 currentState->Update() 时,这将调用最顶层的重写函数,如果你想调用类方法中的任何父类函数,只需指定 ie。状态::更新(); 调用函数时。

于 2012-08-29T22:10:12.747 回答