【发布时间】:2012-08-24 14:05:13
【问题描述】:
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。
【问题讨论】:
-
你需要一个虚函数来覆盖任何东西。其他任何事情都只是隐藏。
标签: c++ oop class methods overriding