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

  • 相关阅读:
    基于jquery的弹幕实现
    Cookie在顶级域名、二级域名和三级域名之间共享的情况
    报错:Win10 这台计算机中已经安装了 .NET Framework 4.5.2/4.6.1/4.7.1等等任何版本 或版本更高的更新
    Unity中的Text内容有空格导致换行
    逆波兰表达式
    Java基础03 byte[] 与 16进制字符串之间的转换
    nacos Linux 单机模式配置
    Oracle 常用SQL
    软件安装01 Linux下redis安装
    Java基础04 JSONObject 与范型对象转换
  • 原文地址:https://www.cnblogs.com/fdyang/p/2858747.html
Copyright © 2011-2022 走看看