在C ++中重载继承规则 [英] Overloading rules for inheritance in C++
问题描述
以下不编译(Apple LLVM版本4.2(clang-425.0.28)):
class A {
public:
virtual void foo(){};
virtual void foo(int i){};
};
class B:public A {
public:
virtual void foo(int i)override {foo(); }
};
编译器错误是调用foo (int)。编译器显然认为我想递归调用B :: foo(int),并且不认识到我想调用A :: foo(void)。
但是:
p> 1)为什么会发生?在这种情况下,看起来很明显只是解析为A :: foo()(或在类层次结构中覆盖的函数)。2)更重要的是,对于foo(void)也使用多态后期绑定,指定A :: foo()不是我想要的,B :: foo()当然也会产生编译错误。
先感谢任何启发!
派生类中的名称在基类中隐藏相同的名称类。换句话说,当在 B
的上下文中解析 foo
时,名称查找找到 B: :foo
并停在那里。 A :: foo
未找到。
使用A :: foo; / code>在 B
的定义。
The following does not compile (Apple LLVM version 4.2 (clang-425.0.28)):
class A {
public:
virtual void foo() {};
virtual void foo( int i ) {};
};
class B : public A {
public:
virtual void foo( int i ) override { foo(); }
};
The compiler error is "Too few arguments" for the call to foo() inside B::foo(int). The compiler apparently thinks that I want to recursively call B::foo(int) and does not recognize that I want to call A::foo(void).
The error goes away if I replace the call to foo() by A::foo().
But:
1) Why is this happening? It seems obvious to just resolve to A::foo() in this case (or an overridden function down the class hierarchy).
2) More importantly, if I want to use polymorphic late binding for foo(void) as well, specifying A::foo() is not what I want, B::foo() of course produces a compiler error as well.
Thanks in advance for any enlightenment!
A name in a derived class hides the same name in base classes. In other words, when resolving foo
in the context of B
, name lookup finds B::foo
and stops there. A::foo
is never found.
Add using A::foo;
within B
's definition.
这篇关于在C ++中重载继承规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!