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();//子类不能直接访问父类的保护成员。
    }
    
    
    
     
  • 相关阅读:
    未分类[selenium]常见元素定位
    未分类[selenium]-元素定位不到的原因及解决办法
    1.4测试需求分析
    1.3测试用例设计方法
    1.2软件生命周期&测试流程
    《Python 高级编程》简要读书笔记
    app基本测试要点总结
    python 找出两个列表的相同元素与不同元素
    mysql 8.0之后关于group by 语句报错问题
    selenium webdriver 执行原理
  • 原文地址:https://www.cnblogs.com/zhangdongsheng/p/1875305.html
Copyright © 2011-2022 走看看