zoukankan      html  css  js  c++  java
  • Return to the basic 继承(Inheritation)

    通过继承机制,可以利用已有的数据类型来定义新的数据类型。
    所定义的新的数据类型不仅拥有新定义的成员,而且还同时拥有旧的成员。
    我们称已存在的用来派生新类的类为基类(base class),又称为父类。由已存在的类派生出的新类称为派生类(derived class),又称为子类。

    继承的通用形式:

    class derived-class:access base-class{
     //
    }



    access 是可选的,
    - 默认的话,是private (派生类是class). 或 public (派生类是struct).
    - 如果使用的话,必须是 public,private 或 protected.

    基类的访问控制

    #include <iostream>
    using namespace std;
    
    class base_class{
     int i,j;
    public:
     void set(int a, int b){
      i=a;
      j=b;
     }
     void show(){
      cout<<i<<" "<<j<<"\n";
     }
    };
    
    class derived_class:public base_class{  
     int k;
    public:
     derived_class(int x){
      k=x;
     }
     void show_k(){
      cout<<k<<"\n";
     }
    };
    
    int main(){
     derived_class ob(3);
     ob.set(1,2);  //访问基类的成员函数.
     ob.show();    // 将输出 1 2 
    
     ob.show_k();  //访问派生类的成员函数. 将输出 3 
     return 0;
    }
    
    

    使用保护成员 (protected)
    - protected成员可以被同类中的其他成员访问,也可以被派生类的成员访问。

    Q.What's the difference between public, protected, and private members of a class ?
    A.Private members are accessible only by (1)members and (2)friends of the class.
      Protected members are accessible by (1)members and (2)friends of the calss and by (3)members and friends of derived classes.
      Public members are accessible by everyone.
     
    多重继承
    -派生类可以从两个或多个基类中继承.

    #include <iostream>
    using namespace std;
    
    class base_class1{
    
    public:
    	base_class1(){
    		cout<<"Constructing base_class1\n";
    	}
    	~base_class1(){
    		cout<<"Destructing base_class1\n";
    	}
    };
    
    class base_class2{
    
    public:
    	base_class2(){
    		cout<<"Constructing base_class2\n";
    	}
    	~base_class2(){
    		cout<<"Destructing base_class2\n";
    	}
    };
    
    class derived_class:public base_class1,public base_class2{
    
    public:
    	derived_class(){
    		cout<<"Constructing derived_class\n";
    	}
    	~derived_class(){
    		cout<<"Destructing derived_class\n";
    	}
    };
    
    int main(){
    	derived_class ob;
    	return 0;
    }
    


    输出结果:
    Constructing base_class1
    Constructing base_class2
    Constructing derived_class
    Destructing derived_class
    Destructing base_class2
    Destructing base_class1

  • 相关阅读:
    tomcat调优
    使用Docker部署Spring Boot项目
    java配置ueditor中解决“未找到上传文件”错误提示
    java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
    spring01
    android中的wrap_content,match_parent, fill_parent
    RPC和http
    Failed to read artifact descriptor for xxx
    Error processing condition on org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafWebMvcConfiguration.resourceUrlEncodingFilter
    springboot的自动配置
  • 原文地址:https://www.cnblogs.com/fdyang/p/2858747.html
Copyright © 2011-2022 走看看