#include<iostream>
using namespace std;
class Automobile
{
private:
int power;
public:
Automobile(int power=150)
{
this->power=power;
cout <<"Automobile constructing."<< endl;
}
void show()
{ cout <<"power: "<< power;}
};
class Car:virtual public Automobile
{
private:
int seat;
public:
Car(int power, int seat): Automobile(power)
{
this-> seat= seat;
cout <<"Car constructing. "<< endl;
}
void show()
{
cout <<"car: ";
Automobile::show();
cout <<" seat: "<< seat << endl;
}
};
class Wagon: virtual public Automobile
{
private:
int load;
public:
Wagon(int power, int load): Automobile( power)
{
this->load=load;
cout<<"Wagon constructing."<<endl;
}
void show()
{
cout<<"wagon:";
Automobile::show();
cout<<" load: "<<load<< endl;
}
};
class StationWagon: public Wagon,public Car
{
public:
StationWagon(int Cpower, int Wpower, int seat, int load)
:Car(Cpower, seat), Wagon(Wpower, load)
{ cout<<" Stationwagon constructing."<< endl; }
void show()
{
cout <<"Stationwagon: "<<endl;
Car::show();
Wagon::show();
}
};
int main()
{
StationWagon SH(105,108,3,8);
SH.show();
return 0;
}
程序输出结果为:
Automobile constructing.
Wagon constructing.
Car constructing.
Stationwagon constructing.
Stationwagon:
car: power: 150 seat: 3
wagon:power: 150 load: 8
这段代码中,Car和Wagon结构都一样,为什么StationWagon(int Cpower, int Wpower, int seat, int load)
:Car(Cpower, seat), Wagon(Wpower, load)调用的时候是先调用Wagon在调用Car?
StationWagon类继承了Car和Wagon类,Car和Wagon类都继承了Automobile类。由于Car和Wagon类都是虚拟继承Automobile类的,所以在构造StationWagon对象时,只会调用一次Automobile类的构造函数,避免了多次继承造成的问题。
在调用StationWagon的构造函数时,先调用Wagon的构造函数,再调用Car的构造函数。因为在定义StationWagon类时,先继承了Wagon类,再继承了Car类,所以在构造StationWagon对象时,先调用Wagon的构造函数,再调用Car的构造函数。