目录
- 1.封装
- 2.继承
- 3.多态
1.封装
封装,封装我认为是对于世界某一具有共性的物体的抽象。比如说动物,我们可以将它的属性和方法抽象出来,动物的身体高度,动物的年龄,那么这些都是属于它属性的一部分,而动物还会叫,还会动,那么这些就属于它的一个方法。在这个过程中,我们可以将其细节隐藏起来,只能通过类的固定接口去使用它,这样的话其实就是说封装可以隐藏实现细节,使得代码模块化;
封装的含义:封装是实现面向对象程序设计的第一步,封装就是将数据或函数等集合在一个个的单元中(我们称之为类)。被封装的对象通常被称为抽象数据类型。
封装的作用:封装的作用在于保护或者防止代码(数据)被我们无意中破坏。在面向对象程序设计中数据被看作是一个中心的元素并且和使用它的函数结合的很密切,从而保护它不被其它的函数意外的修改。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Animal { public: Animal(){} Animal(const string& name, const int& age) { this->name = name; this->age = age; } void showAge() { cout << "age:" << this->age << endl; } void showName() { cout << "name:" << this->name << endl; } void getAge(const int& age) { this->age = age; } void getName(const string& name) { this->name = name; } private: string name; int age; };
2.继承
以上面的Animal为父类,我们可以让老虎(Tiger)类去继承它。这样的话老虎类可以拥有父类Animal中的属性和方法了。
也就是说,继承实现代码和数据的复用,复用的实现在已有的代码和数据的基础上扩展。并且继承分为:公有继承、保护继承、私有继承。
下面是一个公有继承的例子:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13class Tiger :public Animal { }; int main() { Tiger animal; animal.getAge(18); animal.getName("ntt"); animal.showAge(); animal.showName(); return 0; }
3.多态
多态则是为了实现:接口重用。
然后多态分为静态多态和动态多态。
静态多态:不同的实参调用其相应的同名函数。
动态多态:动态多态主要由虚函数实现。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29#include <iostream> using namespace std; class Animal { public: virtual void call() { cout << "I'm Animal..." << endl; } }; class Tiger :public Animal { public: void call() { cout << "I'm Tiger..." << endl; } }; void say(Animal &animal) { animal.call(); } int main() { Animal animal; Tiger tiger; say(animal); say(tiger); return 0; }
运行结果:
多态总结:
①:多态的基础是继承
②:虚函数是实现多态的关键
③: 虚函数重写(函数覆盖)是多态的必要条件
最后
以上就是酷酷小伙最近收集整理的关于1.C++面向对象的三大特性:封装、继承、多态的全部内容,更多相关1.C++面向对象内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复