【问题标题】:Call derived class method from base class instance从基类实例调用派生类方法
【发布时间】:2016-07-06 16:46:58
【问题描述】:

我正在尝试使用多态性,从基类实例调用派生的“add”方法。

但它仍然想运行基类 RealThing "add" 方法。

我期待派生类 RealThingNextVersion "add" 方法。

#include <iostream>
#include <string>
using namespace std;

class VirtualObject
{
public:
    virtual void load() {
        cout << "Nothing to load." << endl;
    }

    void import(string file) {
        //here some importing stuff
    }
};

class RealThing :public VirtualObject
{
private:
    string file;

protected:
    int id;

public:
    RealThing(string fileName = "data.txt") { file = fileName; }

    void load() {
        this->import(this->file);
        cout << "Thing data loaded." << endl;
    }

    virtual void add(int id) {
        cout << "Added V1: " << id << endl;
    };
};

class RealThingNextVersion : public RealThing
{
public:
    string desc;

public:
    virtual void add(int id, string desc) {
        cout << "Added V2: " << id << " with description " << desc <<  endl;
    };
};


int main() {
    RealThing rt;
    RealThingNextVersion rtv;

    RealThing* r;
    r = &rt;
    r->load(); // OK., returns: Thing data loaded.
    r->add(11); // OK., returns: Added V1: ...

    r = &rtv;
    r->add(22, "info"); // Here "Error: too many arguments in function call" 
    // it still want's to run RealThing "add",
    // and I was expecting RealThingNextVersion "add"


    system("pause");
}

【问题讨论】:

    标签: c++ class inheritance polymorphism derived-class


    【解决方案1】:

    RealThingNextVersion 中的addRealThing 中的调用签名(不同的参数)不同,因此它是不同的函数,而不是add 的覆盖。如果在函数声明中添加 override 关键字

    virtual void add(int id, string desc) override;
    

    使用最近的编译器,编译器会告诉你你没有覆盖任何东西。

    【讨论】:

    • 那么如何在RealThingNextVersion类中创建add方法的版本,但是有2个参数,可以通过多态从基类调用?
    • @BlueMark 你需要在基类中有一个2参数add
    猜你喜欢
    • 2019-07-25
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2014-03-17
    • 2011-05-11
    • 2012-04-16
    • 2014-02-15
    • 2013-03-28
    相关资源
    最近更新 更多