虚拟基类的创建顺序 [英] Virtual base classes order of creation

查看:84
本文介绍了虚拟基类的创建顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

struct A1 {
    A1() { std::cout << "A1, "; }
};

struct A2 {
    A2() { std::cout << "A2, "; }
};

struct AA1 : virtual A1,  A2 {
    AA1() { std::cout << "AA1, "; }
};

struct AA2 : A1, virtual A2 {
    AA2(){ std::cout << "AA2, "; }
};

struct B : AA1, virtual AA2 {
    B() { std::cout << "B "; }
};

int main() {
    B b;
}

运行此代码时,答案是:

A1 A2 A1 AA2 A2 AA1 B

我想了解第一个创建的A1在哪里.

我知道在非虚拟类之前先调用虚拟类的规则,但是首先出现A1的问题困扰着我.

解决方案

第一个A1来自B的(非虚拟)基础AA1的(虚拟)基础的初始化.. >

B的所有虚拟基数首先被初始化,并且依次是A1A2AA2. (AA2的初始化产生输出A1 AA2.)然后是直接基,只有一个直接基,AA1(其初始化打印A2 AA1),最后是类本身,打印.所有虚拟基础都首先出现,然后只有其余的非虚拟基础.

I have the following problem:

struct A1 {
    A1() { std::cout << "A1, "; }
};

struct A2 {
    A2() { std::cout << "A2, "; }
};

struct AA1 : virtual A1,  A2 {
    AA1() { std::cout << "AA1, "; }
};

struct AA2 : A1, virtual A2 {
    AA2(){ std::cout << "AA2, "; }
};

struct B : AA1, virtual AA2 {
    B() { std::cout << "B "; }
};

int main() {
    B b;
}

When you run this code, the answer is:

A1 A2 A1 AA2 A2 AA1 B

I want to understand where is the first A1 created.

I know the rule that the virtual classes are called before non - virtual classes but that first A1 is the problem that is bothering me.

解决方案

The first A1 results from the initialization of the (virtual) base of the (non-virtual) base AA1 of B.

All the virtual bases of B are initialized first, and they are, in order, A1, A2 and AA2. (The initialization of AA2 results in the output A1 AA2.) Then come the direct bases, of which there is only one, AA1 (whose initialization prints A2 AA1), and finally the class itself, printing B. All the virtual bases come first, and then only the remaining non-virtual ones.

这篇关于虚拟基类的创建顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆