-2

为什么“hello world”打印了三遍?我不清楚 C++ 结构中的虚拟继承。

#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;
}
4

2 回答 2

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 希望对您有所帮助!

于 2013-11-10T11:27:38.263 回答
0

我对反对票和侮辱性的回应感到震惊。

D有四个基类。其中,mid1有一个基类,virtual BS,和mid2 has one base class,虚拟基站. There are no other uses ofvirtual BS . Somid1 andmid2 share one copy of aBS object as their virtual base.mid3 has a **non**-virtual base,BS ; this is not shared. Andmid4has a 虚拟基类,BS;这也不是共享的。所以有 的三个副本BS:一个是 and 的虚拟基础mid1mid2一个是 的非虚拟基础mid3,一个是 的非虚拟基础mid4。三个BS对象,三个构造函数调用,三个“hello world”。

于 2013-11-10T13:33:11.510 回答