c++ - 关于标准中虚函数描述的一个问题

标签 c++ inheritance c++17 language-lawyer virtual-functions

#include <iostream>
struct A { 
    virtual void f(){
        std::cout<<"1\n";
    } 
};
struct B : A {

};
struct C : A { 
    void f(){
        std::cout<<"abc\n";
    } 
};
struct D : B, C { 

}; 
int main(){
  D mostDerived{};
  D* ptr = &mostDerived;
  B* bptr = ptr;
  A* aptr = bptr;
  aptr->f();
}

考虑上面的代码,outcome1 .但是,由于标准的说法,我对这个结果表示怀疑:
class.virtual#def:final_overrider

For convenience we say that any virtual function overrides itself. A virtual member function C​::​vf of a class object S is a final overrider unless the most derived class of which S is a base class subobject (if any) declares or inherits another member function that overrides vf.

class.derived#def:inheritance

Members of a base class other than constructors are said to be inherited by the derived class. Constructors of a base class can also be inherited as described in [namespace.udecl].

IIUC,考虑 A 类型的基类子对象在 B 和 C 中作为A1 , A2分别。在我的示例中,最派生类是 D ,根据上面的规则,对于类B , 最后的覆盖是 A::f这是继承自 A , 类 C , 最后的覆盖是 C::f在类 C 中声明, 和类 D , 它源自 BC , 因此它将从 B 继承这些成员和 C .自 C::f覆盖 A::f , 所以根据规则 unless **the most derived class of which S is a base class subobject** (if any) declares or **inherits another member function that overrides vf** ,其中考虑 A1作为S (即 A1 是类 D 的子对象),其中 D继承了 another member function that overrides vf这是C::f .这意味着,子对象的最终覆盖 A1应该是 C::f ,因此,我想知道为什么结果不是 abc而不是 1

另一个问题是:

struct A { 
    virtual void f(){
        std::cout<<"1\n";
    } 
};
struct B : A {
  void f(){}
};
struct C : A { 
    void f(){}
};
struct D : B, C { 

}; 

两者都是 B::fC::f重写虚函数 A::f , 但它们不会相互覆盖,所以函数会做 D继承?或者两者都由 D 继承?

如果我遗漏了什么,如何正确阅读上述规则。或者对于第一个问题,上述规则是否确实不清楚造成误解?

最佳答案

... A virtual member function C​::​vf of a class object S is a final overrider unless the most derived class of which S is a base class subobject (if any) declares or inherits another member function that overrides vf.

引用的规则可能存在误导性,因此存在缺陷。

vf 仅仅被 任何 类型 B 的基重写应该是不够的,但它应该被特别重写为 < em>那个基础子对象。在您的示例中,有两个 A 类型的基本子对象,其中一个覆盖了 A::f 而另一个没有覆盖。

so which the function does D inherits? or both are inherited by D?

两者都是继承的。

关于c++ - 关于标准中虚函数描述的一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63992216/

相关文章:

c++ - C++中的数组乘法

c++ - 是否通过名称和定义明确的引用在表达式中多次修改对象?

inheritance - Swift 协议(protocol)继承和泛型函数

c++ - 表达式f()>g()的值,当f&g修改同一个全局变量undefined或unspecified时?

c++ - std::variant 和 boost::variant 有什么区别?

c++ - CMake FetchContent 不复制库

C++测量执行时间

c++ - 用于在 C++ 中访问数组的代码混淆

java - 使用继承(使用抽象类)在自定义框架内为子类提供一小部分方法的更优雅的方式?

java - 使用 Java 8 在运行时选择具体实现