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
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17