继承的概念和意义

  • 类和类之间的关联关系

  • 组合关系:整体与部分的关系

  • 继承关系(父子关系)

  • 组合关系的特点

  • 将其它类的对象作为类的成员使用

  • 当前类的对象与成员对象的生命期相同
  • 成员对象在用法上与普通对象完全一致

  • 面向对象中的继承指类之间的父子关系

  • 子类拥有父类的所有属性和行为

  • 子类就是一种特殊的父类
  • 子类对象可以当作父类对象使用
  • 子类中可以添加父类没有的方法和属性
  • C++中通过下面的方式描述继承关系
1 class Parent
 2 {
 3     int mv;
 4 public:
 5     void method();
 6 };
 7  
 8 class Child : public Parent//描述继承关系
 9 {
10  
11 };
  • 重要的规则:

  • 子类就是一个特殊的父类

  • 子类对象可以直接初始化父类对象
  • 子类对象可以直接赋值给父类对象

  • 继承的意义
    继承是C++中代码复用的重要手段,通过继承,可以获得父类的所有功能,并且可以在子类中重写已有功能,或者添加新功能

  • 小结:

  • 继承是面向对象中类之间的一种关系

  • 子类拥有父类的所有属性和行为
  • 子类对象可以作为父类对象使用
  • 子类中可以添加父类没有的方法和属性
  • 继承是面向对象中代码复用的重要手段
    例:
1 // 继承.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
 2 //
 3 #include <iostream>
 4 #include <string>
 5 using namespace std;
 6 class Parent
 7 {
 8         string age;
 9         string name;
10         string height;
11         string sex;
12 public:
13         Parent()
14         {
15                cout << "we are parent!!" << endl;
16         }
17         Parent(string _age,string _name,string _height,string _sex)
18         {
19                age    = _age;
20                name   = _name;
21                height = _height;
22                sex    = _sex;
23         }
24         void HELLO()
25         {
26                cout << "hello world" << endl;
27                cout << "my name is " << name << endl;
28                cout << "my age is " << age << endl;
29                cout << "my height is " << height << endl;
30                cout << "my sex is " << sex << endl;
31         }
32 };
33 class Child : public Parent
34 {
35 public:
36         Child()
37         {
38                cout << "we are child" << endl;
39         }
40 };
41 int main()
42 {
43         
44         Parent Father("48","mingxing","180cm","man");
45         Father.HELLO();
46         Child CHENGE;
47         //子类可以初始化父类
48         Parent Mother = CHENGE;
49 }

运行结果:hello worldmy name is mingxingmy age is 48my height is 180cmmy sex is manwe are parent!!we are child原文链接: https://www.cnblogs.com/chengeputongren/p/12240682.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/192490

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午6:04
下一篇 2023年2月12日 下午6:04

相关推荐