Why do I need to redeclare overloaded virtual functions?(为什么我需要重新声明重载的虚函数?)
问题描述
我有一个带有两个重载函数 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();}
};
这篇关于为什么我需要重新声明重载的虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我需要重新声明重载的虚函数?


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30