//---------main.cpp------------
#include <iostream>
#include <string>
//多重继承
using namespace std;
class Furniture
{
protected:
int weight;
public:
Furniture(){} //构造函数
void setWeight(int i){weight = i;}
int getWeight(){return weight;}
};
class Bed : public Furniture
{
public:
Bed(){weight=0;}//构造函数
void sleep(){std::cout<<"Sleeping ..."<<endl;}
};
class Sofa : public Furniture
{
public:
Sofa(){weight = 0;}//构造函数
void watchTV(){std::cout<<"Watch TV ..."<<endl;}
};
class SleeperSofa : public Bed,public Sofa
{
public:
SleeperSofa(){}//构造函数
void foldOut(){std::cout<<"Fold out the sofa"<<endl;}
};
int main(int argc,char **argv)
{
SleeperSofa ss;
ss.Sofa::setWeight(20);
std::cout<<"ss.Sofa::getWeight() is "<<ss.Sofa::getWeight()<<endl;
ss.Bed::setWeight(10);
std::cout<<"ss.Bed::getWeight()is "<<ss.Bed::getWeight()<<endl;
/*--上面SleeperSofa的weight没有实现公用,没有实现沙发床的功能--*/
<span style="white-space:pre"> </span>//ss.setWeight(20); //错
//std::cout<<"SleeperSofa weight is "<<ss.getWeight()<<endl; //错
return 0;
}
ss.Sofa::getWeight() is 20
ss.Bed::getWeight()is 10
请按任意键继续. . .
Furniture -- >weight
/ \
/ \
Bed Sofa
\ / \ /
SleeperSofa
虚拟继承:virtual
SleeperSofa只需对应一个Furniture对象,所以我们也希望它只含有一个Furniture副本。且该副本又要共享Bed和Sofa的成员函数和数据成员。
</pre><pre name="code" class="cpp">//---------main.cpp------------
#include <iostream>
#include <string>
//多重继承
using namespace std;
class Furniture
{
protected:
int weight;
public:
Furniture(){} //构造函数
void setWeight(int i){weight = i;}
int getWeight(){return weight;}
};
class Bed : virtual public Furniture
{
public:
Bed(){weight=0;}//构造函数
void sleep(){std::cout<<"Sleeping ..."<<endl;}
};
class Sofa : virtual public Furniture
{
public:
Sofa(){weight = 0;}//构造函数
void watchTV(){std::cout<<"Watch TV ..."<<endl;}
};
class SleeperSofa : public Bed,public Sofa
{
public:
SleeperSofa(){}//构造函数
void foldOut(){std::cout<<"Fold out the sofa"<<endl;}
};
int main(int argc,char **argv)
{
SleeperSofa ss;
//ss.Sofa::setWeight(20);
//std::cout<<"ss.Sofa::getWeight() is "<<ss.Sofa::getWeight()<<endl;
//ss.Bed::setWeight(10);
//std::cout<<"ss.Bed::getWeight()is "<<ss.Bed::getWeight()<<endl;
ss.setWeight(20);
std::cout<<"Sleeper weight is "<<ss.getWeight()<<endl;
/*--上面SleeperSofa的weight实现公用了,实现沙发床的功能--*/
return 0;
}
Sleeper weight is 20
请按任意键继续. . .
含有多继承的构造函数,按以下顺序被调用:
(1)任何虚拟基类的构造函数按照他们被继承的顺序构造。
(2)任何非虚拟基类的构造函数按照他们被继承的顺序构造。
(3)任何成员对象的构造函数按照他们的声明顺序构造。
(4)类自己的构造函数。
若一个类中,含有虚拟继承,则构造首先从虚拟基类开始。
构造一个 SleeperSofa ss;
其对象构造的顺序是:
(1)Furniture对象;
(2)Bed对象,不管构造函数的初始化列表是否把Bed排在Sofa后面
(3)Sofa对象;
(4)SleeperSofa对象。
1