【问题标题】:Editing functions in child class子类中的编辑功能
【发布时间】:2019-09-12 14:27:50
【问题描述】:

我想编辑一个继承函数name(),并确保在被child 的实例调用时,继承函数info() 将调用child::name() 而不是parent::name()

class parent {
public:
    string name() { return "parent"; }

    void info() {
        cout << "This class is " << name() << endl;
    }
};

class child : public parent {
public:
    string name() { return "child"; }
};

int main() {
    parent p;
    child c;
    p.info(); // outputs "parent"
    c.info(); // outputs "parent" - I want "child"
}

如何让c.info() 使用child::name()?在info() 之外,我永远不需要name(),而且我真的不想在子类中复制info(),因为我试图避免在我的实际问题中重复相当长的代码块。

【问题讨论】:

  • parent::name() 需要标记为virtualchild::name() 应标记为override

标签: c++ inheritance polymorphism


【解决方案1】:

你声明​​了一个非多态函数

如果你父级的成员函数f() 不是virtual,则它不是多态的。所以如果这个函数被父函数的另一个函数调用,就会调用parent::f()

如果该函数被子函数中的另一个函数f() 隐藏,签名完全相同,并且如果该函数被子函数的另一个函数调用,则将调用child::f()

有趣的是,如果你直接为一个对象调用函数,就会调用该对象声明类型的函数。

多态函数

如果你想让你的函数多态,你必须在父级中将它定义为virtual。假设它在孩子中被覆盖。在这种情况下,当您调用f() 时,它始终是为对象的真实类型定义的f()

class parent {
public:
    virtual string name() { return "parent"; }

    ...
    }
};

class child : public parent {
public:
    string name() override { return "child"; }
};

使用这个程序,你会得到这样的结果:

This class is parent
This class is child

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-06
    • 2019-05-08
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多