请解释为什么“Hello world”打印3次?

时间:2013-11-10 11:07:42

标签: c++ virtual-inheritance

为什么“hello world”打印三次?我不清楚在使用C ++的struct中继承virtual。

#include<iostream>
using namespace std;

struct BS{
    BS() {
        cout << "hello world" << endl;
    }

    unsigned int color;
};

struct mid1 : virtual public BS { };
struct mid2 : virtual public BS { };
struct mid3 : public BS { };
struct mid4 : public BS { };

struct D : public mid1, public mid2, public mid3, public mid4 { };

int main() {
    D d;
    return 0;
}

2 个答案:

答案 0 :(得分:2)

考虑这个例子。 它更容易理解。当您创建派生类的对象时,该对象首先调用基类的构造函数,然后调用它自己的构造函数。

#include "stdafx.h"
#include<iostream>
#include <iomanip>
#include <conio.h>
using namespace std;

struct BaseClass{
    BaseClass() 
    {
        cout << "hello world of base class" << endl;
    }
};

struct DerivedClass1 : virtual public BaseClass { };

struct DerivedClass2 : virtual public BaseClass
{
    DerivedClass2()
    {
        cout<<"hello world of derived class"<<endl;
    }
};

int main() {

    //when you create a member of Base Class it calls just its own constructor. 
    cout<<"Creating an object of BaseClass  : "<<endl;
    BaseClass a;
    cout<<"Done \n \n";

    //when you create a member of Derived class1 it calls constructor of base class      once and then calls
    //its own constructor but as nothing is defined in its default constructor nothing      is printed.
    cout<<"Creating an object of DerivedClass1 (Pure Virtual)  : "<<endl;
    DerivedClass1 b;
    cout<<"Done \n \n";

    //when you create a member of Derived class2 it calls constructor of base class once and then calls
    //its own constructor because its derived. (See how hello world is printed twice , one for base and one for derived)
    cout<<"Creating an object of DerivedClass2  : "<<endl;
    DerivedClass2 c;
    cout<<"Done \n \n";

    getch();
    return 0;
 }

这是输出http://codepad.org/zT3I1VMu 希望它有所帮助!

答案 1 :(得分:0)

我对这些沮丧和侮辱性的回应感到震惊。

D有四个基类。其中,mid1有一个基类,virtual BSmid2 has one base class,虚拟BS . There are no other uses of虚拟BS . So mid1 and mid2 {{1} } BS share one copy of a mid3 object as their virtual base. BS has a **non**-virtual base, mid4 ; this is not shared. And - 虚拟基地,has a;这也是不共享的。因此,BS有三个副本:一个是BSmid1的虚拟基础,一个是mid2的非虚拟基础,另一个是mid3的非虚拟基础。三个mid4个对象,所以三个构造函数调用,所以三个“hello world”。