gpt4 book ai didi

C++ 多态性和覆盖

转载 作者:搜寻专家 更新时间:2023-10-31 00:00:32 27 4
gpt4 key购买 nike

我很难在 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;
}

如果您更改“State currentState”以创建 MenuState 的对象,代码将按我的要求工作,但是我需要它成为父类,以便我可以将当​​前状态设置为我将在其中创建的其他状态 future ,例如 GameState。

谢谢。

最佳答案

由于切片,多态性不适用于普通对象。您必须使用引用或(智能)指针。在您的情况下,指针不能重新分配引用:

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;
}

在您的代码中:

State currentState;
MenuState menuState;

currentState = menuState;

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

关于C++ 多态性和覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993531/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com