C++学习——继承与派生「建议收藏」
2023-06-13 09:11:02 时间
大家好,又见面了,我是你们的朋友全栈君。
文章目录
普通继承
例题:定义一个名为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;
}
结果如下:
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/171001.html原文链接:https://javaforall.cn
相关文章
- C++学习之路—— C++异常处理机制
- C++学习——CString,char * ,string的相互转换
- C++学习——memset函数详解
- C++学习——数据类型(强制)转换详解
- C++ 输入的是1.3变1.29999995问题
- C++ 新增的 stl 容器实用方法,你知道几个?(文末赠送 C++20 书籍)
- C++异常的介绍和分析
- C++ docker_docker部署mysql
- C++ 新特性学习(五) — 引用包装、元编程的类型属性和计算函数对象返回类型
- C++ 新特性学习(八) — 原子操作和多线程库[多工内存模型]
- 准大三学生给想学习C++同学的学习路线
- c 线程安全的单例模式-std string与线程安全_这才是现代C++单例模式简单又安全的实现
- C++为什么能重夺年度语言?
- 【C++ 语言】面向对象 ( 类定义 | 限制头文件引用次数 | 构造方法 | 析构方法 )
- 【C++】map、set、multimap、multiset的介绍和使用
- C++面向对象程序设计(谭浩强)第三章 怎样使用类和对象 第一节学习笔记
- C++ 下 Halcon 与 OpenCV 图像的转换
- C++ STL学习之容器set和multiset (补充材料)详解编程语言
- C++11 lambda表达式学习详解编程语言
- C++ binomial_distribution二项式分布随机数用法解析
- C++私有成员函数
- C++ auto(类型推导)精讲
- 用g++命令执行C++多文件项目
- VC++开发中完美解决头文件相互包含问题的方法解析