C++ 教程 - 06 类的封装、继承、多态

文章目录

封装

  • 在private/protected 模块放置数据或者底层算法实现;
  • 在public块提供对外接口,实现相应的功能调用;
  • 类的封装案例
cpp 复制代码
#include <iostream>
using namespace std;


// 类的定义 一般放在头文件
class Stu {

public: // 公有权限 接口

	void setAge(const int& age) {
		this->age = age;
	}

	const int& getAge() const {
		return age;
	}

private: // 数据封装
	int age;
};

int main() {
	// 创建对象
	Stu s1; 
	s1.setAge(20);
	cout << s1.getAge() << endl;
	return 0;
}

继承

  • 将一个类的成员变量、成员函数,应用到另一个类中,实现复用;
  • 支持多继承,同python一样;而 java 仅支持单继承;
  • 继承修饰符public、protected、private; 若不写修饰符,则默认private继承;
  • public继承,基类中的public、protected、private 保持不变;
  • protected继承,基类中的public、protected、private 变为protected、protected、private
  • private继承, 基类中的public、protected、private全部变为private;
cpp 复制代码
#include <iostream>
#include <string>
using namespace std;


// 基类
class People {
public:
	string name;
	People(const string& name, const int& age, const double& height) {
		this->name = name;
		this->age = age;
		this->height = height;
		cout << "父类完成初始化" << height << endl;
	}
	void printName() const {
		cout << "name:" << name << endl;
	}

	void printAge() const {
		cout << "age:" << this->age << endl;
	}

	void printHeight() const {
		cout << "height:" << this->height << endl;
	}

protected:
	int age;

private:
	double height;
};

// 类的定义 一般放在头文件
class Stu: public People { // 公有继承(经常使用)
public: // 可多个块
	int num; // 若未放在public等修饰符下, 默认私有
	Stu(const string& name, const int& age, const double&heigh): People(name, age, heigh){// 显式调用父类的有参构造,否则隐式调用父类的无参构造;
		// 子类的构造 初始化
		this->num = 102;
	}

	void printAge() const {// 子类方法中,只能访问继承的public/protected 成员,private成员无法访问,但可以通过父类的方法到父类代码中访问;
		cout << "age:" << this->age << endl;
	}
	/*void printHeight() const {
		cout << "height:" << this->height << endl;
	}  不可访问继承的私有 */

};


int main() {

	string name = "jack";
	int age = 20;
	double height = 23.5;
	// 创建对象
	Stu s1(name, age, height);  // 父类的构造方法 完成对私有变量的初始化
	s1.printName();
	s1.printAge();
	s1.printHeight(); // 在父类中访问私有	
	return 0;
}

多态

  • 多个子类继承父类中的方法,分别实现方法的重写;
  • 父类中采用 virtual 声明为虚函数;
  • 函数体赋值为=0,则为纯虚函数;
cpp 复制代码
在这里插入代码片
相关推荐
csdn_aspnet6 小时前
C++ 使总距离最短的最佳点位置(Optimum location of point to minimize total distance)
c++·算法
代码民工正电荷7 小时前
JAVA重要知识点和集合
java·开发语言
星恒随风7 小时前
C++11 加餐(4)并发支持库——condition_variable 条件变量与生产者消费者模型
开发语言·c++
利威尔xu7 小时前
Go map 并发十连问:多 goroutine 同时读写触发 fatal error,进程直接崩溃
开发语言·golang
你不知道我是谁?8 小时前
GESP C++ 补充知识:浮点数格式化输出(%f/%e/%g)与 fmod 浮点余数实战
开发语言·c++
九蝶科技8 小时前
运费分摊的二开实现:BigDecimal 精确分摊 + 尾差补齐 + 暂估调整
开发语言·python
Ryan-Zhong9 小时前
一次接入 16 个平台:视频链接元数据解析 API 的 Python 实战与踩坑记录
开发语言·python·dreamweaver
Rabitebla9 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树
linux·运维·服务器·c++·笔记·学习·算法
无限聚核10 小时前
PHP 对接美团、抖音团购核销接口:预核销、核销、重试和撤销一份代码跑通,无限聚核
开发语言·php·美团·团购核销接口
WL学习笔记11 小时前
继承(C++)
c++·继承