zoukankan      html  css  js  c++  java
  • 继承的概念和意义

    • 类和类之间的关联关系
    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
     
    主要记录的是学习听课的笔记
  • 相关阅读:
    HDU 2089 不要62
    HDU 5038 Grade(分级)
    FZU 2105 Digits Count(位数计算)
    FZU 2218 Simple String Problem(简单字符串问题)
    FZU 2221 RunningMan(跑男)
    FZU 2216 The Longest Straight(最长直道)
    FZU 2212 Super Mobile Charger(超级充电宝)
    FZU 2219 StarCraft(星际争霸)
    FZU 2213 Common Tangents(公切线)
    FZU 2215 Simple Polynomial Problem(简单多项式问题)
  • 原文地址:https://www.cnblogs.com/chengeputongren/p/12240682.html
Copyright © 2011-2022 走看看