C++的典型特征是封装、继承和多态。
封装顾名思义就是将成员函数、成员变量等放在一个用class定义的类当中,形成一个整体。
继承也就是某一个类(子类)继承了另一个类(基类)的某些属性,可以是public、private或protected中的成员函数、成员变量等。其中子类所定义的对象在使用时就可以直接调用基类中的某些属性。
那么多态又是什么呢?除了有与重载相似的功能外,我的理解是多态还包含了一个虚函数可以在父类的指针指向子类对象的前提下,通过父类的指针调用子类的成员函数的功能,其中关键词是virtual(虚函数)。例如:以下代码中Children继承了Father,基类中在第5行定义了一个叫show()的虚函数,11行子类中也定义了叫show()的虚函数。主函数中第20行定义了类型为Father类的指针p,而内存中开辟的是Children类的空间。由于指针指向的是Children类所以p->show()调用的是Children中的show()函数。
1. #include<iostream>
2. using namespace std;
3. class Father {
4. public:
5. virtual void show() {
6. cout << "father show" << endl;
7. }
8. };
9. class Children : public Father {
10. public:
11. virtual void show() {
12. cout << "children show" << endl;
13. }
14. };
15. int main() {
16. Father *father = new Father();
17. father->show(); // 调用父类的show函数
18. Children *children = new Children();
19. children->show(); // 调用子类的show函数
20. Father *p = new Children();
21. p->show(); // 调用哪个类中的show函数?
22. return 0;
23. }
反之,如下代码所示。第5行、第11行都没有定义virtual类,所以在主函数中当第20行定义了一个类型为Father类的指针p,内存中开辟的是Children类的空间时,由于p是Father类的指针,因此这会调用Father类中的show函数。至于为什么会调用Father中的show()函数,可以去了解一下指针的本质。
以上的总结如果有不对的地方还请各位斧正,觉得对你学习C++有帮助还请点赞加收藏。
1. #include<iostream>
2. using namespace std;
3. class Father {
4. public:
5. void show() {
6. cout << "father show" << endl;
7. }
8. };
9. class Children : public Father {
10. public:
11. void show() {
12. cout << "children show" << endl;
13. }
14. };
15. int main() {
16. Father *father = new Father();
17. father->show(); // 调用父类的show函数
18. Children *children = new Children();
19. children->show(); // 调用子类的show函数
20. Father *p = new Children();
21. p->show(); // 调用哪个类中的show函数?
22. return 0;
23. }