【问题标题】:Virtual function not overloading in derived class [duplicate]派生类中的虚函数未重载[重复]
【发布时间】:2020-07-16 16:59:09
【问题描述】:
    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();

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

【问题讨论】:

    标签: c++ function oop inheritance overloading


    【解决方案1】:

    这是因为CommandRoot getCmdList(int n) 返回一个CommandRoot 对象。要使虚函数工作,您需要一个引用或指针。

    尝试更改为

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

    【讨论】:

      猜你喜欢
      • 2012-11-17
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多