类的继承简介

一、声明格式:

class 子类名:继承方式(public private protected) 父类名{子类成员表}

二、继承过程:

吸取父类成员------>改造父类成员------>添加新成员

三、作用:

子类会继承父类中的方法(不包括构造和析构函数)与属性

cpp 复制代码
#include<iostream>
using namespace std;
class rectangle{//基类/父类 
	protected:
		double length,width;
	public:
		rectangle(double l,double w):length(l),width(w){}
		~rectangle(){
			cout<<"调用父类中的析构函数!"<<endl;
		};
		void show1(){
			cout<<"周长:"<<2*(length+width)<<"\t面积:"<<length*width<<endl; 
		};
};
class cuboid:public rectangle{//子类:吸取基类成员 
	private:
		double height;//添加新成员 
	public:
		cuboid(double l,double w,double h):rectangle(l,w),height(h){}
		~cuboid(){
			cout<<"调用子类中的析构函数!"<<endl;
		} 
		void show2(){//改造基类成员 
			cout<<"周长:"<<2*(length+width)<<"\t面积:"<<length*width<<"\t体积:"<<length*width*height<<endl; 
		}
}; 

int main()
{
	cuboid c2(1,2,3);//子类对象 
	c2.show1();
	c2.show2(); 
}

运行结果:

相关推荐
C^h3 小时前
c++ string
开发语言·c++
raindayinrain3 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的3 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao3 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
小徐不徐说4 小时前
C++ 接口与插件设计:从工厂注册到 Qt 动态插件
数据库·c++·qt·系统架构·程序设计
大都督会赢的5 小时前
C++第一节课
开发语言·c++
UIU1145 小时前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
TMedical5 小时前
MedPlanning 截骨模拟矫形功能
c++·图像处理·人工智能·qt·健康医疗
qq_406981036 小时前
共享变量一 关于extern与const
开发语言·c++
chari克里8 小时前
QT5.15.2 + msvc2022部署全流程说明(windows可联网环境)
开发语言·c++·qt