继承的概念和意义

  • 类和类之间的关联关系
  1. 组合关系:整体与部分的关系
  2. 继承关系(父子关系)
  • 组合关系的特点
  1. 将其它类的对象作为类的成员使用
  2. 当前类的对象与成员对象的生命期相同
  3. 成员对象在用法上与普通对象完全一致
  • 面向对象中的继承指类之间的父子关系
  1. 子类拥有父类的所有属性和行为
  2. 子类就是一种特殊的父类
  3. 子类对象可以当作父类对象使用
  4. 子类中可以添加父类没有的方法和属性
  5. C++中通过下面的方式描述继承关系
 1 class Parent
 2 {
 3     int mv;
 4 public:
 5     void method();
 6 };
 7  
 8 class Child : public Parent//描述继承关系
 9 {
10  
11 };
  • 重要的规则:
  1. 子类就是一个特殊的父类
  2. 子类对象可以直接初始化父类对象
  3. 子类对象可以直接赋值给父类对象
  • 继承的意义
继承是C++中代码复用的重要手段,通过继承,可以获得父类的所有功能,并且可以在子类中重写已有功能,或者添加新功能
  • 小结:
  1. 继承是面向对象中类之间的一种关系
  2. 子类拥有父类的所有属性和行为
  3. 子类对象可以作为父类对象使用
  4. 子类中可以添加父类没有的方法和属性
  5. 继承是面向对象中代码复用的重要手段
例:
 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 world
my name is mingxing
my age is 48
my height is 180cm
my sex is man
we are parent!!
we are child
 

猜你喜欢

转载自www.cnblogs.com/chengeputongren/p/12240682.html