繁体   English   中英

C ++编译器(cl)看不到具有相同子方法名称的父虚拟方法

[英]C++ Compiler (cl) does not see parent virtual method with same child method name

我有一个C ++代码,同时使用继承和函数重写,这是代码:

#include <iostream>
#include <string>

using namespace std;

class Parent
{
    protected:
        virtual void G() const = 0;
    public:
        virtual void G(const string& s) const final { G(); }
};

class Child : public Parent
{
    protected:
        virtual void G() const override { cout<<"Child G"; }
};

int main()
{
    Child *c = new Child();
    c->G("test");
    return 0;
}

编译时出现错误: Child::G: function does not take 1 arguments 但是当我像这样使用Parent指针时:

Parent *c = new Child();

有用。 另外,如果我更改公共G方法的名称,它也可以工作。

两种方法使用相同的名称( G )有什么问题?

您需要using声明将父成员介绍给孩子:

class Child : public Parent
{
    protected:
        virtual void G() const override { cout<<"Child G"; }
    public:
        using Parent::G;
};

解决此问题的方法的确是using声明指出,将Parent的方法通过using声明引入Child类的范围。 至于为什么会这样,仅是编译器在搜索与您的函数调用匹配的方法时如何在范围内搜索的问题。 发生的情况如下:

  • Child *c = new Child(); c->G("test"); Child *c = new Child(); c->G("test"); ,编译器会看到对Child类型的对象的某些方法G的调用。 然后,它搜索Child的范围以查找匹配项。
  • 编译器在探究Child的范围时,仅看到Child::G() const 没有看到Parent::G(const std::string&) const ,即使您希望通过继承将其包含在内,也处于不同的范围内 从某种意义上说, Child::G 遮盖了 Parent::G 没有候选者匹配,编译器将一直在搜索Parent范围。
  • 因此,编译器很高兴找到Child::G 但是,此函数不接受任何参数,因此您尝试使用"test"对其进行调用。 然后,由于参数不匹配,函数调用失败。

如前所述,您需要将Parent::G置于与Child::G相同的作用域内,以便按预期进行重载,并在Child体内using Parent::G

资料来源: https : //isocpp.org/wiki/faq/strange-inheritance#overload-derived

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM