有人可以解释下面的多重继承,为什么即使使用参数化构造函数构造车辆类,也不调用 d 类的参数化构造函数。
#include<iostream>
using namespace std;
class d{
public:
d()
{
cout<<"in default constructor of d"<<endl;
}
d(int x)
{
cout<<"in parametrized constructor of d"<<endl;
}
void a()
{
cout<<"a function of d";
}
};
class Vehical:virtual public d
{
public:
Vehical(int x):d(x)
{
cout<<"In paramterized constructor of Vehical" <<endl;
}
void a()
{
cout <<"a function of Vehical class"<<endl;
}
Vehical()
{
cout<<"default constructor of Vehical"<<endl;
}
};
class now: virtual public d
{
public:
void a()
{
cout <<"a function of now "<<endl;
}
now()
{
cout<<"Default constructor of now" <<endl;
}
};
class car :public Vehical, public now
{
public:
car();
car(int y):Vehical(y)
{
};
//using d::a;
using Vehical::a;
};
int main()
{
car ob(1);
ob.a();
return 0;
}
输出:
in default constructor of d
In paramterized constructor of Vehical
Default constructor of now
期望:它应该调用 D 的参数化构造函数而不是默认的,因为我们是通过传递参数来构造车辆,它确实调用了 D 类的参数化构造函数。
另外,如果我们删除一个类的虚拟,我们又会遇到钻石问题吗?为什么这样?
场景1):如果我们从车辆类中删除虚拟,我们有以下输出
in default constructor of d
in parametrized constructor of d
In paramterized constructor of Vehical
Default constructor of now
a function of Vehical class
同样在上面的输出中,为什么首先调用默认构造函数,然后对 d 类进行参数化?还在输出中,为什么首先调用 d 的构造函数,然后调用车辆,现在调用类构造函数。
期望:它应该首先调用 d 的参数化构造函数,然后调用车辆的参数化构造函数,然后调用 d 的默认构造函数,然后调用 now 的默认构造函数
场景 2)现在我们从 now 类中删除 virtual 并且我们有输出,其中 d 的默认构造函数被调用而不是参数化?
in default constructor of d
In paramterized constructor of Vehical
in default constructor of d
Default constructor of now
a function of Vehical class
期望:它应该在第一行调用 D 的参数化构造函数而不是默认构造函数。