⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 多重继承.txt

📁 钱能主编 C++程序设计教程(第一版) 该书习题的答案代码
💻 TXT
字号:
//**************************
//**      ch17_1.cpp      **
//**************************
#include <iostream.h>

class Bed
{
public:
	Bed():weight(0) {}

	void Sleep()
	{
		cout<<"Sleeping..."<<endl;
	}
	void SetWeight(int i) {weight=i;}
protected:
	int weight;
};

class Sofa
{
public:
	Sofa():weight(0) {}

	void WatchTV()
	{
		cout<<"Watching TV."<<endl;
	}
	void SetWeight(int i) {weight=i;}
protected:
	int weight;
};

class SleepSofa:public Bed,public Sofa
{
public:
	SleepSofa() {}
	void FoldOut()
	{
		cout<<"Fold out the sofa."<<endl;
	}
};

void main()
{
	SleepSofa ss;
	ss.WatchTV();
	ss.FoldOut();
	ss.Sleep();
}

//**************************
//**      ch17_2.cpp      **  could't pass the compilation
//**************************
#include <iostream.h>

class Furniture
{
public:
	Furniture() {}
	void SetWeight(int i){weight=i;}
	int GetWeight() {return weight;}
protected:
	int weight;
};

class Bed:public Furniture
{
public:
	Bed() {}

	void Sleep()
	{
		cout<<"Sleeping..."<<endl;
	}
};

class Sofa:public Furniture
{
public:
	Sofa() {}

	void WatchTV()
	{
		cout<<"Watching TV."<<endl;
	}
};

class SleepSofa:public Bed,public Sofa
{
public:
	SleepSofa() {}
	void FoldOut()
	{
		cout<<"Fold out the sofa."<<endl;
	}
};

void main()
{
	SleepSofa ss;
	ss.WatchTV();
	ss.FoldOut();
	ss.Sleep();
	ss.SetWeight(20);  //
	cout<<ss.GetWeight()<<endl;  //
}

//**************************
//**      ch17_3.cpp      **
//**************************
//virtual inheritance
#include <iostream.h>

class Furniture
{
public:
	Furniture() {}
	void SetWeight(int i){weight=i;}
	int GetWeight() {return weight;}
protected:
	int weight;
};

class Bed:virtual public Furniture
{
public:
	Bed() {}

	void Sleep()
	{
		cout<<"Sleeping..."<<endl;
	}
};

class Sofa:virtual public Furniture
{
public:
	Sofa() {}

	void WatchTV()
	{
		cout<<"Watching TV."<<endl;
	}
};

class SleepSofa:public Bed,public Sofa
{
public:
	SleepSofa() {}
	void FoldOut()
	{
		cout<<"Fold out the sofa."<<endl;
	}
};

void main()
{
	SleepSofa ss;
	ss.WatchTV();
	ss.FoldOut();
	ss.Sleep();
	ss.SetWeight(20);
	cout<<ss.GetWeight()<<endl;
}

//**************************
//**      ch17_5.cpp      **
//**************************
#include <iostream.h>

class Animal
{
public:
	Animal() {}
	void eat() { cout<<"eat."<<endl; }
};

class Giraffe: private Animal
{
public:
	Giraffe() {}
	void StretchNeck() { cout<<"stretch neck."<<endl; }
	void take()
	{
		eat();
	}
};

void Func(Giraffe &an)
{
	an.take();
}

void main()
{
	Giraffe gir;
	gir.StretchNeck();
	Func(gir);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -