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

    1.组合关系

    组合关系的特点

    a.将其它类的对象作为当前类的成员使用
    b.当前类的对象与成员对象的生命周期相同
    c.成员对象在用法上与普通对象完全一致

    eg:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Memory
    {
    public:
    	Memory()
    	{
    		cout << "Memory()" << endl;
    	}
    	~Memory()
    	{
    		cout << "~Memory()" << endl;
    	}
    };
    
    class Disk
    {
    public:
    	Disk()
    	{
    		cout << "Disk()" << endl;
    	}
    	~Disk()
    	{
    		cout << "~Disk()" << endl;
    	}   
    };
    
    class CPU
    {
    public:
    	CPU()
    	{
    		cout << "CPU()" << endl;
    	}
    	~CPU()
    	{
    		cout << "~CPU()" << endl;
    	}    
    };
    
    class MainBoard
    {
    public:
    	MainBoard()
    	{
    		cout << "MainBoard()" << endl;
    	}
    	~MainBoard()
    	{
    		cout << "~MainBoard()" << endl;
    	}    
    };
    
    class Computer
    {
    	Memory mMem;
    	Disk mDisk;
    	CPU mCPU;
    	MainBoard mMainBoard;
    public:
    	Computer()
    	{
    		cout << "Computer()" << endl;
    	}
    	void power()
    	{
    		cout << "power()" << endl;
    	}
    	void reset()
    	{
    		cout << "reset()" << endl;
    	}
    	~Computer()
    	{
    		cout << "~Computer()" << endl;
    	}
    };
    
    int main()
    {   
    	Computer c;
    	
    	return 0;
    }
    

    2.继承关系

    面向对象中的继承关系指类之间的父子关系
    a.子类拥有父类的所有属性和行为
    b.子类是一种特殊的父类
    c.子类对象可以当做父类对象使用
    d.子类中可以添加父类没有的方法和属性

    语法:

    class Parent
    {
        int mv;
    public:
        void method () 
        {
        }
    }
    
    class Child : public Parent        //描述继承关系
    {
    };
    

    eg:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Parent
    {
        int mv;
    public:
        Parent ()
        {
            cout << "Parent()" << endl;
            mv = 100;
        }
        
        void method ()
        {
            cout << "mv = " << mv << endl;
        }
    };
    
    class Child : public Parent
    {
    public:
        void hello()
        {
            cout << "I'm Child class" << endl;
        }
    };
    int main()
    {
        Child c;
        
        c.hello();
        c.method();
        
        return 0;
    }
    

    重要规则

    a.子类就是一个特殊的父类
    b.子类对象可以直接初始化父类对象
    c.子类对象可以直接赋值给父类

    eg: 上诉例子中的类

    Child c;
    Parent p1 = c;
    Parent p2;
    
    p2 = c;
  • 相关阅读:
    python之scrapy篇(三)
    python之scrapy篇(二)
    python之scrapy篇(一)
    matlib调用python时转py格式为matlib格式
    ubuntu18.40 rtx2080ti安装显卡驱动/cuda/cudnn/tensorflow-gpu
    pytorch导入错误so: undefined symbol: _Z11libshm_initPKc
    yolo_v3训练自己的模型(人脸及deep-sort)(或自己数据集)
    python-图像处理(映射变换)
    python编译pyc工程--导包问题解决
    python(leetcode)-14最长公共前缀
  • 原文地址:https://www.cnblogs.com/huangdengtao/p/11934824.html
Copyright © 2011-2022 走看看