多重继承.txt

来自「钱能主编 C++程序设计教程(第一版) 该书习题的答案代码」· 文本 代码 · 共 200 行

TXT
200
字号
//**************************
//**      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 + =
减小字号Ctrl + -
显示快捷键?