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;
  • 相关阅读:
    P4396 [AHOI2013]作业 分块+莫队
    B1965 [Ahoi2005]SHUFFLE 洗牌 数论
    B1970 [Ahoi2005]Code 矿藏编码 暴力模拟
    B1968 [Ahoi2005]COMMON 约数研究 数论
    B1237 [SCOI2008]配对 贪心 + dp
    B1108 [POI2007]天然气管道Gaz 贪心
    B1734 [Usaco2005 feb]Aggressive cows 愤怒的牛 二分答案
    B1012 [JSOI2008]最大数maxnumber 分块||RMQ
    HAOI2007 反素数
    NOIP2009 Hankson的趣味题
  • 原文地址:https://www.cnblogs.com/huangdengtao/p/11934824.html
Copyright © 2011-2022 走看看