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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值