解决多继承三角问题实例(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为16
	cout << 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;
}

有虚继承就会有虚基类表指针 而指针大小为4字节 所以sofa为16

SofaBed 虚继承继承俩个父类 产生俩个虚基类表指针8字节,所以SofaBed为8+12=20字节

父类或者子类中有一个virtual就有一个虚基类表指针,就多4字节

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(){}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值