[英]C++: inheriting overloaded non-virtual method and virtual method both with the same name causes problem
I am trying to inherit two equally named methods with different parameter lists to a derived class.我试图将两个具有不同参数列表的同名方法继承到派生类。 One of them is virtual and overridden in the derived class, the other one is non-virtual.其中一个是虚拟的并在派生类中被覆盖,另一个是非虚拟的。 Doing so, i get a compile error while trying to access the non-virtual method of the base class from an derived class object.这样做时,我在尝试从派生类对象访问基类的非虚拟方法时遇到编译错误。
Here is the code snippet这是代码片段
class Base {
public:
void f() {
cout << "[Base::f()]" << endl;
}
virtual void f(int arg) {
cout << "[Base::f(" << arg << ")]" << endl;
}
};
class Deriv : public Base {
public:
virtual void f(int arg) {
cout << "[Deriv::f(" << arg << ")]" << endl;
}
};
int main() {
Deriv d;
d.f(-1);
d.f(); // <<-- compile error
return 0;
}
which produces the following compile error:这会产生以下编译错误:
error: no matching function for call to 'Deriv::f()'错误:没有用于调用“Deriv::f()”的匹配函数
note: candidates are: virtual void Deriv::f(int)注意:候选人是: virtual void Deriv::f(int)
I am not an expert in C++, but until now I thought to be right in making the assumption that member methods can be completely distinguished by their signatures.我不是 C++ 的专家,但直到现在我认为假设成员方法可以通过它们的签名完全区分是正确的。 Thus, the non-virtual method Base::f() should not be overridden and should remain accessible.因此,非虚拟方法 Base::f() 不应被覆盖并且应保持可访问性。 Am I wrong with this?我错了吗?
Here are some interesting/additional comments on that:以下是一些有趣的/额外的评论:
So, since I already know how to avoid this compile error, I am mainly interested in why this error happens!所以,既然我已经知道如何避免这个编译错误,我主要感兴趣的是为什么会发生这个错误!
In Deriv
, add this:在Deriv
,添加以下内容:
using Base::f;
In addition to the link given by @DumbCoder, you can find more details in my answer to a similar question: Overriding a Base's Overloaded Function in C++除了@DumbCoder 提供的链接之外,您还可以在我对类似问题的回答中找到更多详细信息: Overriding a Base's Overloaded Function in C++
Derived class function hides the base function defintion.派生类函数隐藏了基函数定义。 Detailed explaination as to why and how关于原因和方式的详细解释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.