2012-10-20 86 views
2

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

谢谢。

+0

什么是你的问题? – alestanis

回答

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

在您的代码:

State currentState; 
MenuState menuState; 

currentState = menuState; 

分配切片menuState - 它基本上只是复制了它的State部分currentState ,失去所有其他类型的信息。

+0

是的,C++与C#的不同之处在于,默认情况下C#用户定义的类型都是“引用类型”。将'Foo myFoo;'从C#翻译成C++会产生类似于'Foo * myFoo = new Foo;'(取决于C#中'Foo'的实际定义,我理解C#添加了用户定义的值类型)。 – bames53

+0

工作过的魅力!快速响应,信息也!我很感激帮助。 – Questioning

2

更改您的代码:

int main() 
{ 
    State *currentState; 

    currentState = new MenuState(); 
    currentState->drawState(); 

    system("pause"); 
    delete(currentState) 
    return 0; 
} 
+1

没有必要进行动态分配(应尽可能避免这种情况),此外,此代码会泄漏内存。 –

+0

@LuchianGrigore你说这是因为这个OP的代码没有实现多态破坏(virtual-dtors)吗?如果是这样,那么*删除者*的错误,而不是OP的类呢? (首先为完全不必要的动态分配+1)。 – WhozCraig

+0

@WhozCraig我的评论的第二部分不再适用(最初,答案没有'delete currentState')。现在,它只会导致未定义的行为(因为你陈述的原因)。 –