Skip to content

Commit

Permalink
Create 2024-2-4-C++-面向对象的四大特性.md
Browse files Browse the repository at this point in the history
  • Loading branch information
TangLongbin committed Feb 4, 2024
1 parent 5316309 commit 0a217b8
Showing 1 changed file with 95 additions and 0 deletions.
95 changes: 95 additions & 0 deletions _posts/C/C++/2024-2-4-C++-面向对象的四大特性.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
---
layout: post
title: C++ 面向对象的四大特性
subtitle: 封装、继承、多态、抽象
category: C/C++
date: 2024-2-4
author: Longbin
cover: https://raw.githubusercontent.com/isocpp/logos/64ef037049f87ac74875dbe72695e59118b52186/cpp_logo.svg
cover_author: ISO C++
cover_author_link: https://github.com/isocpp/logos
tags:
- C/C++
- 面向对象
---
## 封装

C++ 能够将数据与函数(方法)封装在类(Class)中,对外部提供**有限**接口,对内部数据进行**保护**,降低模块耦合,提升维护性。

```cpp
class People{
public:
People();
~People();
virtual void Do() = 0;
private:
int age;
float height, weight;
protected:
string name;
}
```
## 继承
一个子类能够继承一个父类的属性和方法,子类能够访问父类 `public` 与 `protected` 中的成员,并且可以**重载**或者**增加**新成员,提高代码复用率与拓展性。
```cpp
class Student:People{
public:
Student(float _grade);
~Student();
void Do();
void ChangeNameTo(string NewName);
private:
float grade;
}
class Parent:People{
public:
void Do();
void GiveNameTo(People &_people);
}
```

## 多态

一个对象表现出多种形态的特性即为多态,通常由**重载****虚函数**实现。父类(基类)指针能够指向不同的子类(派生类),调用**同样方法(同一接口******实现**不同功能**

```cpp
int main(){
People *people;

Student student;
Parent parent;

people = &student;
people -> Do();

people = &parent;
people -> Do();

return 0;
}
```

## 抽象

将不同对象的共同特性/特征提取出来形成**抽象类**,在类中定义数据与接口,不实现具体功能,而是被派生类继承并拓展。

```cpp
class People{
}

class Male:People{
}

class Boy:Male{
}

class Female:People{
}

class Girl:Female{
}
```

0 comments on commit 0a217b8

Please sign in to comment.