gpt4 book ai didi

C++:覆盖还是重载?

转载 作者:行者123 更新时间:2023-11-30 01:09:55 26 4
gpt4 key购买 nike

我有两个类代表某些方法的上下文。

class BaseContext {};
class DerivedContext : public BaseContext {};

我有一个基类:

class MyBase {
protected:
virtual void doSome(BaseContext* context);
};

派生类:

class MyDerived : public MyBase {
protected:
virtual void doSome(DerivedContext* context) override; // Overriding
virtual void doSome(DerivedContext* context); // Overloading?
};

因为 DerivedContext 派生自 BaseContext,所以看起来我正在覆盖 doSome。但这也可能是重载...

  1. 哪个是正确的?我在这里是覆盖还是重载?
  2. 因此,如果我输入 (MyBase* my = new MyDerived())->doSome(new DerivedContext()),我应该得到什么?

最佳答案

这既不是覆盖也不是重载。由于参数的类型不同,MyDerived::doSome 只是隐藏 MyBase::doSome

1.1. Since DerivedContext derives from BaseContext, it might seems that I am overriding doSome.

没有。这是标准中列出的覆盖的先决条件。 $10.3/2 Virtual functions[class.virtual] :

(强调我的)

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list ([dcl.fct]), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides110 Base::vf.

110) A function with the same name but a different parameter list (Clause [over]) as a virtual function is not necessarily virtual and does not override.

事实上与override specifier你会得到一个 compile error对于这种情况。例如

error: 'doSome' marked 'override' but does not override any member functions

1.2. But it might also be an overloading...

can't overload根据 unqualified name lookup 的规则跨范围运行(除非使用 using-declaration 将名称引入同一范围)。

  1. Thus, if I type (MyBase* my = new MyDerived())->doSome(new DerivedContext()), what should I get?

MyBase::doSome() 将被调用,因为您在 MyBase* 上调用它。这不是最重要的,所以这里没有动态调度发生。

LIVE

请注意参数 DerivedContext* 将隐式转换为 BaseContext* 然后传递给函数。顺便说一句 (MyBase* my = new MyDerived())->... 是无效语法。

关于C++:覆盖还是重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39162226/

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