旨在调用派生类的虚函数,但错误地称为基类的虚函数。对象未切片

时间:2019-05-21 09:16:00

标签: c++

我正在尝试为课程项目实施基于回合的游戏。该游戏具有“状态”基类,并从中得出实际状态,例如“中毒”,“瘫痪”或“'死”(这是出错的测试用例)。

需要先设置状态,然后再通过移动对象将其施加给角色对象,并且SetupStatus()函数在状态类的不同派生类之间有所不同。

问题是,当我尝试调用从基类“状态”派生的“扼流”类(SetupStatus())的choke::SetupStatus()函数时,它总是调用该函数status::SetupStatus()。该函数在cmove::LaunchMove(...)中被调用。

我在哪里做错了?

我首先错过了虚拟声明。我添加了它,但是并不能解决问题。

main.cpp

int main() {
    cmove aqua_ball = AquaBall();
    field TestField;
    character Irrawa = IRRAWA();
    character Mew = MEW();
    aqua_ball.LaunchMove(&Irrawa, &Mew, &TestField);
}

cmove.cpp

void cmove::LaunchMove(character *speller, character *taker, field *thisField) {
    //some other codes...
    if (slf_adStat.size() != 0) {
        for (int i = 0; i < slf_adStat.size(); i++) {
            status tempStatus = slf_adStat[i];
            cout << tempStatus.get_information() << endl; //Output tempStatus info
            tempStatus.SetupStatus(speller, taker, thisField);//Where the function call goes wrong
            cout << tempStatus.get_information() << endl; //Output tempStatus info

            (*speller).add_status(tempStatus);
        }
    }
    //some other codes...
};

status.h

class status{
public:
    string sta_name, sta_info;
    //some other codes...

    virtual void SetupStatus(character* selfCharacter, character* oppoCharacter, field* currentField);
    string get_information();

    //some other codes...
};

class choke : public status{
public:
    choke(){
        sta_name = "CHOKE";
        sta_info = "Reduce speed by 15. Last 3 turns.";
        //some codes...
    }
    virtual void SetupStatus(character* selfCharacter, character* oppoCharacter, field* currentField);
    //some codes...
};

status.cpp

void status::SetupStatus(character* selfCharacter, character* oppoCharacter, field* currentField){
    cout << "General status setup..."<< endl;
}
string status::get_information(){
string output = "[" + sta_name + "]" + ":\n" + sta_info + "\nLEFT:" + to_string(nT) + "turns\n";
return output;
}
void choke::SetupStatus(character* selfCharacter, character* oppoCharacter, field* currentField){
    sta_ds = -15;
    cout << sta_ds << "Choke status setup..." << endl;
}

输出:

[CHOKE]:
Reduce speed by 15. Last 3 turns.
LEFT:3turns

General status setup...
[CHOKE]:
Reduce speed by 15. Last 3 turns.
LEFT:3turns

由于SetupStatus()函数之前和之后的tempStatus对象均按预期进行打印,因此tempStatus是一个扼流类对象,因此这与对象切片无关。

如果需要,可以在这里找到所有代码: https://github.com/Irrawa/godsFighting

0 个答案:

没有答案