1. 程式人生 > >一個c++多重繼承的例子

一個c++多重繼承的例子

/*一個多重繼承的例子,以電腦為例,電腦由硬碟,記憶體,cpu構成,以下的所有函式均直接寫在類中*/
#include <iostream>
#include <string>
using namespace std;

/*定義Hdd類表示硬碟*/
class Hdd
{
private:
	int rpm;//轉速
	int size;//容量
	int cache;//快取
public:
	Hdd(int r, int s, int c)
	{
		rpm = r;
		size = s;
		cache = c;
	}
	~Hdd(){}
	void show_Hdd()
	{
		cout << "\nHdd" << endl;
		cout << "rpm = " << rpm << "rpm" << endl;
		cout << "size = " << size << "G" << endl;
		cout << "cache = " << cache << "MB" << endl;
	}
};

/*定義處理器類*/
class CPU
{
private:
	float C_frequency;//主頻
	int L1;//一級快取
	int L2;//二級快取
	int L3;//三級快取
public:
	CPU(float f, int l1, int l2, int l3)
	{
		C_frequency = f;
		L1 = l1;
		L2 = l2;
		L3 = l3;
	}
	~CPU(){}
	void show_CPU()
	{
		cout << "\nCPU" << endl;
		cout << "C-frequency = " << C_frequency << "GHz"<< endl;
		cout << "L1 = " << L1 << "MB"<< endl;
		cout << "L2 = " << L2 << "MB"<< endl;
		cout << "L3 = " << L3 << "MB"<< endl;
	}
};

/*定義記憶體類*/
class Memery
{
private:
	float M_frequency;//頻率
	int MemerySize;//記憶體大小
	string DDR_Type;//介面型別
public:
	Memery(float mf, int ms, string Dt)
	{
		M_frequency = mf;
		MemerySize = ms;
		DDR_Type = Dt;
	}
	~Memery(){}
	void show_Memery()
	{
		cout << "\nMemery" << endl;
		cout << "M-frequency = " << M_frequency << "GHz" << endl;
		cout << "MemerySize = " << MemerySize << "GB" << endl;
		cout << "DDR_Type = " << DDR_Type << endl;
	}
};

/*定義電腦類,並多重繼承Hdd,CPU,和Memery類*/
class Computer: public Hdd, public CPU, public Memery
{
private:
	string owner;//電腦所有人
	string tradmark;//商標
public:
	/*注意建構函式的形式*/
	Computer(string o, string tm, int hr, int hs, int hc, float cf, int cl1, int cl2, int cl3, float mf, int ms, string mdf):Hdd(hr, hs, hc), CPU(cf, cl1, cl2, cl3), Memery(mf, ms, mdf)
	{
		owner = o;
		tradmark = tm;
	}
	~Computer(){}
	void show_all()
	{
		cout << "owner = " << owner << endl;
		cout << "tradmark = " << tradmark << endl;
		show_CPU();
		show_Memery();
		show_Hdd();
	}
};

int main(int argc, char const *argv[])
{
	Computer desktop("BillGates", "Thinkpad", 7200, 500, 32, 2.6, 1, 2, 3, 1.3, 4, "DDR3");//將所有引數寫入建構函式
	desktop.show_all();//顯示所有資訊
	return 0;
}