解决多继承三角问题实例(SofaBed)

来源:互联网 发布:故宫淘宝 编辑:程序博客网 时间:2024/06/14 03:06

解决多继承三角问题实例(SofaBed)


主函数:

#include "stdafx.h"#include <iostream>using namespace std;#include "Sofa.h"#include "Bed.h"#include "SofaBed.h"//为解决//sofabed len wid high  两份数据 冗余//        discription() 访问问题int _tmain(int argc, _TCHAR* argv[]){Sofa sf(3,2,1);sf.sit();sf.discription();//有虚继承就会有虚基类表指针 而指针大小为4字节 所以sofa为16cout << sizeof(Sofa) << endl; Bed bed(1,2,3);bed.sleep();bed.discription();cout << sizeof(Bed) << endl;//Bed Sofa 这些中间类,并不受virtual的影响 像普通类一样使用 //virtual发生的阶段 在生成孙子类的时候生效SofaBed sb(2,3,3);sb.sit();sb.sleep();sb.discription();//SofaBed 虚继承继承俩个父类 产生俩个虚基类表指针 8字节cout << sizeof(SofaBed) << endl; //12+8=20字节return 0;}



Furniture.h

#pragma once#include <iostream>using namespace std;class Furniture{public:Furniture(int l,int w,int h);~Furniture();void discription();private:int len;int wid;int high;};

Furniture.cpp

#include "Furniture.h"Furniture::Furniture(int l, int w, int h){len = l;wid = w;high = h;}void Furniture::discription(){cout << "len: " << len << endl;cout << "wid: " << wid << endl;cout << "high: " << high << endl;}Furniture::~Furniture(){}

Bed.h

#pragma once#include <iostream>using namespace std;#include "Furniture.h"class Bed:virtual public Furniture{public:Bed(int l,int w,int h);~Bed();void sleep();};

Bed.cpp

#include "Bed.h"Bed::Bed(int l, int w, int h):Furniture(l,w,h){}void Bed::sleep(){cout << "go to bed and have a sleep" << endl;}Bed::~Bed(){}

Sofa.h

#pragma once#include <iostream>using namespace std;#include "Furniture.h"class Sofa:virtual public Furniture{public:Sofa(int l,int w,int h);~Sofa();void sit();};

Sofa.cpp

#include "Sofa.h"Sofa::Sofa(int l, int w, int h):Furniture(l,w,h){}void Sofa::sit(){cout << "have a sit and have a rest" << endl;}Sofa::~Sofa(){}

SofaBed.h

#pragma once#include <iostream>using namespace std;#include "Bed.h"#include "Sofa.h"class SofaBed:public Sofa,public Bed{public:SofaBed(int l,int w,int h);~SofaBed();};

SofaBed.cpp

#include "SofaBed.h"SofaBed::SofaBed(int l, int w, int h):Sofa(l, w, h), Bed(l, w, h), Furniture(l,w,h){}SofaBed::~SofaBed(){}