C++学习——继承与派生「建议收藏」

C++学习——继承与派生「建议收藏」普通继承例题:定义一个名为Phone的手机类,有如下私有成员变量:品牌、型号、CPU、电池容量,如下成员函数:构造函数初始化手机的信息。在此基础上派生出NewPhone类,派生类增加了两个新的私有数据成员,分别用于表示颜色和价格,增加了一个成员函数用来输出手机信息。代码如下:#include <iostream>#include<string>#include&l…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

文章目录

普通继承

例题:定义一个名为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;
}

结果如下:
结果

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/171001.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号