为什么“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;
}
答案 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 BS
和mid2 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
有三个副本:一个是BS
和mid1
的虚拟基础,一个是mid2
的非虚拟基础,另一个是mid3
的非虚拟基础。三个mid4
个对象,所以三个构造函数调用,所以三个“hello world”。