This question already has answers here:
What is object slicing?

(18个回答)


在8个月前关闭。



    class CommandRoot {
protected:
    string cmdString = "";
    string title = "";
    string tags = "";
    string description = "";

public:
    string getCmdString() {
        return cmdString;
    }
    string getTitle() {
        return title;
    }
    string getTags() {
        return tags;
    }
    string getDescription() {
        return description;
    }

    virtual bool onTrigger() {
        return 1;
    }
};

class CmdFirst : public CommandRoot{
public:
    CmdFirst() {
        cmdString = "testing1";
        title = "";
        tags = "";
        description = "";
    }

    bool onTrigger() {
        cout << "C";
        return 0;
    }
};

class Player {
    NPC *target = NULL;
    CommandRoot *cmdList[1];

public:
    Player() {
        cmdList[0] = new CmdFirst();
    }

    CommandRoot getCmdList(int n) {
        return *cmdList[n];
    }

    NPC getTarget() {
        return *target;
    }

    bool setTarget(NPC* t) {
        target = t;
        return 0;
    }

    string listen() {
        string cmd = "";
        cin >> cmd;
        return cmd;
    }
};

int main()
{
    std::cout << "Hello World!\n";

    Player* player = new Player();
    NPC* firstNPC = new NPC();
    player->setTarget(firstNPC);

    bool exit = false;
    do {
        if (player->listen().compare(player->getCmdList(0).getCmdString()) == 0) {
            cout << "A";
            cout << player->getCmdList(0).onTrigger();
        }
        else
        {
            cout << "B";
        }
    } while (exit == false);
}

下一行正在调用父级的虚拟函数,而不是派生类。
cout << player->getCmdList(0).onTrigger();

我有一种感觉,因为数组的数据类型是父类,但这不应该阻止为数组元素分配派生类的数据类型,然后调用该类的函数。

最佳答案

这是因为CommandRoot getCmdList(int n)返回了CommandRoot对象。为了使虚拟功能正常工作,您需要引用或指针。

尝试更改为

CommandRoot& getCmdList(int n) {
    return *cmdList[n];
}

10-07 18:58
查看更多