虚继承中构造函数调用的顺序

2023-09-27C/C++开发问题
9

本文介绍了虚继承中构造函数调用的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

class A {
        int i;
public: 
        A() {cout<<"in A's def const
";};
        A(int k) {cout<<"In A const
";  i = k; }
        };

class B : virtual public A {
public:
        B(){cout<<"in B's def const
";};
        B(int i) : A(i) {cout<<"in B const
";}
        };

class C :   public B {
public:
        C() {cout<<"in C def cstr
";}
        C(int i) : B(i) {cout<<"in C const
";}
        };

int main()
{
        C c(2);
        return 0;
}

这种情况下的输出是

in A's def const
in B const
in C const

为什么这不进入in A const

`它应该遵循 1 arg 构造函数调用的顺序.但是使用 virtual 关键字从 A 派生 B 时实际发生了什么.

`It should follow the order of 1 arg constructor call. But what actually is happening on deriving B from A using virtual keyword.

还有几个问题

即使我删除了上面程序中的 virtual 关键字并删除了所有默认构造函数,它也会出错.那么,为什么它需要 def 构造函数

Even if I remove the virtual keyword in above program and remove all the default constructor it gives error. So, why it needs the def constructor

推荐答案

虚基类的构造函数总是从最派生的类调用,使用它可能传入的任何参数.在你的情况下,最派生的类不会't 为 A 指定初始化器,因此使用默认构造函数.

The constructors for virtual base classes are always called from the most derived class, using any arguments it might pass in. In your case, the most derived class doesn't specify an initializer for A, so the default constructor is used.

这篇关于虚继承中构造函数调用的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6