我很难在C++中使用这个工作,我在C#中管理它,但我没有使用C++,所以我不确定语法。C++多态性和覆盖
这样做的目的是为了一个简单的状态管理器,每个状态从一个称为“状态”的基类继承。
我已经得到压倒一切的工作,但我似乎无法管理多态性方面。那就是我不能有一个对象“State currentState”,并将该对象设置为等于“menuState”,并让它运行所需的函数,我知道这是因为它只是为State类找到签名,但我不确定如何躲开它。这里有一些简化的代码,以便有人能帮助我理解。
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// State.h
class State{
public:
virtual void drawState();
};
// State.cpp
void State::drawState() {
cout << "Base state.\n";
}
// MenuState.h
class MenuState: public State {
public:
virtual void drawState();
};
// MenuState.cpp
void MenuState::drawState() {
cout << "Menu state.\n";
State::drawState();
}
int main()
{
State currentState;
MenuState menuState;
currentState = menuState;
currentState.drawState();
system("pause");
return 0;
}
如果更改“国currentState”创建MenuState的目标,我要求它的代码将工作,但我需要它的父类,这样我可以设置当前状态到其他状态我将在未来创建诸如GameState。
谢谢。
什么是你的问题? – alestanis