C++多态性和覆盖

Que*_*ing 2 c++ polymorphism inheritance overriding

我很难在C++中使用它,我已经用C#进行了管理,但是我没有使用C++,所以我不确定语法.

这个目的是为了一个简单的状态管理器,每个状态都从一个名为"state"的基类继承.

我已经压倒性地工作,但我似乎无法管理多态性方面.那就是我不能有一个对象"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;
}
Run Code Online (Sandbox Code Playgroud)

如果您更改"State currentState"以创建MenuState的对象,则代码将按照我的要求运行,但是我需要它作为父类,以便我可以将当​​前状态设置为将来创建的其他状态,例如作为GameState.

谢谢.

Luc*_*ore 5

由于切片,多态性不能与普通对象一起使用.你必须使用引用或(智能)指针.在您的情况下,无法重新指定作为引用的指针:

int main ()
{
    State* currentState = NULL;
    MenuState menuState;

    currentState = &menuState;
    currentState->drawState(); //calls MenuState::drawState()

    NextState nextState; //fictional class
    currentState = &nextState;
    currentState->drawState(); //calls NextState::drawState()

    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在你的代码中:

State currentState;
MenuState menuState;

currentState = menuState;
Run Code Online (Sandbox Code Playgroud)

赋值切片menuState- 它基本上只是复制它的State一部分currentState,丢失所有其他类型的信息.