为什么我需要重新声明重载的虚函数?
我有一个带有两个重载函数 f(void)
和 f(int)
的基类.Derived
类通过调用 f(void)
实现 f(int)
.Derived2
仅实现 f(void)
.
I have a base class with two overloaded functions f(void)
and f(int)
. The class Derived
implements f(int)
by calling f(void)
. Derived2
implements f(void)
only.
编译器拒绝实现 Derived::f(int)
因为它想调用 f(int)
但我没有提供参数因为我想调用 f(void)
.为什么编译器会拒绝它?为什么添加行 virtual int f(void) = 0;
可以解决我的问题?
The compiler rejects the implementation Derived::f(int)
because it wants to call f(int)
but I provided no arguments because I want to call f(void)
. Why does the compiler reject it? Why does adding the line virtual int f(void) = 0;
fix my problem?
class Base
{
public:
explicit Base(void) {}
virtual ~Base(void) {}
virtual int f(void) = 0;
virtual int f(int i) = 0;
};
class Derived : public Base
{
public:
// provide implementation for f(int) which uses f(void). Does not compile.
virtual int f(int i) {puts("Derived::f(int)"); return f();}
// code only compiles by adding the following line.
virtual int f(void) = 0;
};
class Derived2 : public Derived
{
public:
// overwrite only f(void). f(int) is implemented by Derived.
virtual int f(void) {puts("Derived2::f(void)"); return 4;}
};
int main(void)
{
Base * p = new Derived2();
int i0 = p->f(); // outputs Derived2::f(void) and returns 4
int i1 = p->f(1); // outputs "Derived::f(int) Derived2::f(void)" and return 4
delete p;
return 0;
}
推荐答案
Derived::f
隐藏 Base::f
s.给定Derived::f(int)
的body中的return f();
,在f
这个名字>派生,然后名称查找停止.Base
中的名称将无法找到并参与重载解析.
Derived::f
hides Base::f
s. Given return f();
in the body of Derived::f(int)
, the name f
is found in the scope of Derived
, then name lookup stops. The names in Base
won't be found and participate in overload resolution.
名称查找如下所述检查范围,直到找到至少一个任何类型的声明,此时查找停止并且不再检查范围.
name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.
您可以添加using Base::f;
,将Base
中的名称引入Derived
的范围.
You can add using Base::f;
to introduce the name from Base
into the scope of Derived
.
class Derived : public Base
{
public:
using Base::f;
// provide implementation for f(int) which uses f(void).
virtual int f(int i) {puts("Derived::f(int)"); return f();}
};
相关文章