C++学习之路——继承与派生

普通继承

例题:定义一个名为Phone的手机类,有如下私有成员变量:品牌、型号、CPU、电池容量,如下成员函数:构造函数初始化手机的信息。在此基础上派生出NewPhone类,派生类增加了两个新的私有数据成员,分别用于表示颜色和价格,增加了一个成员函数用来输出手机信息。

代码如下:

#include <iostream>
#include<string>
#include<Windows.h>
using namespace std;

class Phone
{
public:
	string pinpai;
	string xinghao;
	string CPU;
	string dianchi;
	Phone(string s1, string s2, string s3, string s4);
	void Print();
private:
};

Phone::Phone(string s1, string s2, string s3, string s4)
{
	pinpai = s1;
	xinghao = s2;
	CPU = s3;
	dianchi = s4;
}
void Phone::Print()
{
	cout << "手机的品牌是:" << pinpai << endl;
	cout << "手机的型号是:" << xinghao << endl;
	cout << "手机的CPU是:" << CPU << endl;
	cout << "手机的电池容量是:" << dianchi << endl;
}


class NewPhone :public Phone
{
	string color;
	string price;
public:
	NewPhone(string s1, string s2, string s3, string s4, string s5, string s6) :Phone(s1, s2, s3, s4), color(s5), price(s6)
	{
	}
	void Print() {
		Phone::Print();
		cout << "手机的颜色是:" << color << endl;
		cout << "手机的价格是:" << price << endl;
	}
};

int main()
{

	NewPhone B("华为", "mate", "很大", "1000mA", "黄色", "100000");

	B.Print();
	system("pause");
	return 0;
}

结果如下:
在这里插入图片描述

菱形继承

写一个菱形继承,如下图所示:在这里插入图片描述

写出类的具体结构和方法。

//兽王
class AnimalKing 
{

public:
	int weight;
	int height;
	int leg;
	void getWeight() 
	{ 
		cout << "请输入狮虎兽的体重:";
		cin>>weight;
	};
	void getHeight()
	{
		cout << "请输入狮虎兽的身高:";
		cin >> height;
	};
	void getLeg()
	{
		cout << "请输入狮虎兽的腿数:";
		cin >> leg;
	};
};

//老虎
class Tiger : virtual public AnimalKing 
{ 
public:
	void Putweight()
	{
		cout << "继承了老虎的体重"<< weight<< endl;
	}
	void Putheight()
	{
		cout << "继承了老虎的身高" << weight << endl;
	}
	void Putleg()
	{
		cout << "继承了老虎的腿数" << weight << endl;
	}
};

//狮子
class Lion : virtual public AnimalKing
{
public:
	void Putweight()
	{
		cout << "继承了狮子的体重" << weight << endl;
	}
	void Putheight()
	{
		cout << "继承了狮子的身高" << weight << endl;
	}
	void Putleg()
	{
		cout << "继承了狮子的腿数" << weight << endl;
	}
};

//狮虎兽
class Liger : public Tiger, public Lion
{
public:
	~Liger()
	{
		cout << "狮虎兽诞生了!" << endl;
	}
};

int main()
{
	Liger a;
	a.Tiger::getWeight();
	a.Tiger::Putweight();
	a.Lion::getHeight();
	a.Lion::Putheight();
	a.Lion::getLeg();
	a.Tiger::getLeg();
	a.Lion::Putleg();
	a.Tiger::Putleg();

	return 0;
}

结果如下:
结果

发布了22 篇原创文章 · 获赞 26 · 访问量 523

猜你喜欢

转载自blog.csdn.net/weixin_45525272/article/details/104281214