gpt4 book ai didi

C++:继承和重载决议

转载 作者:太空狗 更新时间:2023-10-29 20:00:03 25 4
gpt4 key购买 nike

我正在阅读这里的 C++ 谜题:http://gotw.ca/gotw/005.htm

我不明白他对静态与动态重载解析(或默认参数)的解释,所以我尝试提炼问题并自己编写一些测试:

class Base {
public:
virtual void foo() {cout << "base/no parameters" << endl;}
virtual void foo(int a) {cout << "base/int" << endl;}
};

class Derived : public Base {
public:
void foo() {cout << "derived/no parameters" << endl;}
void foo(double a) {cout << "derived/int" << endl;}
};

int main() {
Base* ptr = new Derived;
ptr->foo();
ptr->foo(1.0);
}

输出是:

derived/no parameters
base/int

怎么在调用foo()的时候,C++似乎识别出它指向的是一个Derived,但是在调用foo(1.0),C++ 在 Derived 类中没有看到 void foo(double a) 函数?

在我看来,存在相互竞争的想法,即 C++ 具有多态性,这解释了第一次调用,但重载解析是在编译时完成的,这解释了第二次调用。

最佳答案

这是 Function Hiding 的经典示例.
派生类中的函数覆盖基类函数当且仅当:

  1. virtual 关键字至少出现在基类函数上。
  2. 派生类中的函数与基类函数具有完全相同的签名。

第二条规则有一个异常(exception),其中 Covariant return types 是允许的。

鉴于以上两条规则:

派生类中的无参数foo()函数覆盖基类foo(),因此动态调度适用于您预期。

带有一个参数的foo(double)版本不会覆盖基类foo(int),它只是隐藏它。由于没有覆盖,因此没有动态调度,编译器仅调用它在基类范围内找到的 foo(int) 函数。

关于C++:继承和重载决议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9124238/

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