zoukankan      html  css  js  c++  java
  • c++特性之一继承

    1. 子类继承父类,父类里的成员可以被子类调用
    #include <iostream.h>
    class Animal
    {
    public:
    	void eat()
    	{
    		cout<<"animal eat"<<endl;
    	}
    
    	void sleep()
    	{
    		cout<<"animal sleep"<<endl;
    	}
    };
    
    class Fish:public Animal
    {
      
    };
    
    void main()
    {
    	Animal an;
    	Fish fh;
    	fh.sleep();
    }

    2.protected 成员被毕继承只能对在子类内部访问,不能直接访问,父类本身也不能访问。

    #include <iostream.h>
    class Animal
    {
    public:
    	void eat()
    	{
    		cout<<"animal eat"<<endl;
    	}
    protected:
    	void sleep()
    	{
    		cout<<"animal sleep"<<endl;
    	}
    public:
    	void breathe()
    	{
    		cout<<"animal breathe"<<endl;
    	}
    };
    
    class Fish:public Animal
    {
    public:
    
    	void test()
    	{
    		sleep();
    	}
      
    };
    
    void main()
    {
    	Animal an;
    	Fish fh;
    	fh.test();//子类可以通过内部成员函数来访问父类的保护成员
    	fh.sleep();//子类不能直接访问父类的保护成员。
    }
    
    3. 继承中私有成员无论怎样都不能被子类访问!
    4.构造函数。构造子类对象时,先执行父类的构造函数,再执行子类的构造函数。析构的顺序正好与其相反 。
    #include <iostream.h>
    class Animal
    {
    public:
    	Animal(){cout<<"Animal construction!"<<endl;}
    	void eat()
    	{
    		cout<<"animal eat"<<endl;
    	}
    protected:
    	void sleep()
    	{
    		cout<<"animal sleep"<<endl;
    	}
    public:
    	void breathe()
    	{
    		cout<<"animal breathe"<<endl;
    	}
    };
    
    class Fish:public Animal
    {
    public:
    	Fish(){cout<<"Fish construction!"<<endl;}
    
    	void test()
    	{
    		sleep();
    	}
      
    };
    
    void main()
    {
    //	Animal an;
    	Fish fh;
    	fh.test();//子类可以通过内部成员函数来访问父类的保护成员
    //	fh.sleep();//子类不能直接访问父类的保护成员。
    }
    5.子类构造要先构造父类。当父类是有参构造函数,子类构造函数无参时,需要在后面加上 :父类的构造函数
    
    #include <iostream.h>
    class Animal
    {
    public:
    	Animal(int height,int weigtht)//带参数的构造函数
    	{cout<<"Animal construction!"<<endl;}
    	void eat()
    	{
    		cout<<"animal eat"<<endl;
    	}
    protected:
    	void sleep()
    	{
    		cout<<"animal sleep"<<endl;
    	}
    public:
    	void breathe()
    	{
    		cout<<"animal breathe"<<endl;
    	}
    };
    
    class Fish:public Animal
    {
    public:
    	Fish():Animal(300,400)
    	{cout<<"Fish construction!"<<endl;}
    
    	void test()
    	{
    		sleep();
    	}
      
    };
    
    void main()
    {
    //	Animal an;
    	Fish fh;
    	fh.test();//子类可以通过内部成员函数来访问父类的保护成员
    //	fh.sleep();//子类不能直接访问父类的保护成员。
    }
    
    
    
     
  • 相关阅读:
    BZOJ4923 K小值查询(splay)
    BZOJ4919 大根堆(动态规划+treap+启发式合并)
    BZOJ4922 Karp-de-Chant Number(贪心+动态规划)
    BZOJ4915 简单的数字题
    BZOJ4921 互质序列
    BZOJ4898/5367 Apio2017商旅(分数规划+floyd)
    BZOJ4899 记忆的轮廓(概率期望+动态规划+决策单调性)
    Educational Codeforces Round 55 Div. 2 翻车记
    166. Fraction to Recurring Decimal
    390. Elimination Game
  • 原文地址:https://www.cnblogs.com/zhangdongsheng/p/1875305.html
Copyright © 2011-2022 走看看