关于虚基类

来源:互联网 发布:windows ssid 编辑:程序博客网 时间:2024/05/21 11:46

在前天所说的内容中,在调用BedRoom可能产生二义性的问题,而虚基类就很好的解决了这个问题。
代码如下:

#include<iostream>#include<string>using namespace std;class Base{private:    int width;    int length;    string name;public:    Base();    Base(string name);    void setWidth(int width);    void setLength(int length);    void showSize();    void showName();    ~Base();};Base::Base(string name){    cout << "调用Base类构造函数" << endl;    this->name = name;}void Base::setWidth(int width){    this->width = width;}void Base::setLength(int length){    this->length = length;}void Base::showSize(){    cout << this->name << "的width=" << width <<"  "<<"length="<< length << endl;}void Base::showName(){    cout << "材料名字为" << this->name << endl;}Base::~Base(){    cout << "调用Base类析构函数" << endl;}class Bed:virtual public Base{private:    string thing1;public:    Bed();    Bed(string name, string thing1);    void showThing1();    ~Bed();};Bed::Bed(string name, string thing1) :Base(name){    this->thing1 = thing1;    cout << "调用Bed类构造函数" << endl;}void Bed::showThing1(){    cout << "Bed拥有的特点:" << this->thing1 << endl;}Bed::~Bed(){    cout << "调用Bed析构函数" << endl;}class Room :virtual public Base{private:    string thing2;public:    Room();    Room(string name, string thing2);    void showThing2();    ~Room();};Room::Room(string name, string thing2) :Base(name){    this->thing2 = thing2;    cout << "调用Room类构造函数" << endl;}void Room::showThing2(){    cout << "Room拥有的特点:" << thing2 << endl;}Room::~Room(){    cout << "调用Room类析构函数" << endl;}class BedRoom :public Bed, public Room{public:    BedRoom(string BedName, string Roomname, string thing1, string thing2, string name) :Bed(BedName, thing1), Room(Roomname, thing2), Base(name)    {        cout << "调用BedRoom类构造函数" << endl;    }    /*void setWidth(int width1, int width2)    {        Bed::setWidth(width1);        Room::setWidth(width2);    }    void setLength(int length1, int length2)    {        Bed::setLength(length1);        Room::setLength(length2);    }    void showSize()    {        Bed::showSize();    }    void showName()    {        Bed::showName();    }*/    ~BedRoom()    {        cout << "调用BedRoom析构函数" << endl;    }};int main(){    {        BedRoom d1("room1", "room2", "small", "big","name");        d1.setLength(10);        d1.setWidth(15);        d1.showName();        d1.showSize();        d1.showThing1();        d1.showThing2();    }        cin.get();        return 0;}

程序运行结果:
这里写图片描述
在这段程序中我们把BedRoom类中与Base类中很多相同的成员删除了,但程序执行结果并无多大差异。另外注意一下,俩个程序中派生类BedRoom构造函数的不同。

原创粉丝点击