gpt4 book ai didi

c++ - 为什么需要重新声明重载的虚函数?

转载 作者:行者123 更新时间:2023-12-02 02:31:05 27 4
gpt4 key购买 nike

我有一个带有两个重载函数 f(void)f(int) 的基类。 Derived 类通过调用 f(void) 实现 f(int)Derived2 仅实现 f(void)

编译器拒绝实现 Derived::f(int) 因为它想调用 f(int) 但我没有提供任何参数,因为我想调用 f(void)。为什么编译器会拒绝它?为什么添加行 virtual int f(void) = 0; 可以解决我的问题?

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。给定 Derived::f(int) 主体中的 return f();,在 范围内找到名称 f >派生,然后 name lookup停止。 Base 中的名称将不会被发现并参与重载解析。

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的范围中。

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();}
};

关于c++ - 为什么需要重新声明重载的虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65018186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com