[英]C++ Virtual Methods: Must I create a virtual method in the parent class for every method that the child and parent do not share?
[英]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.