通过继承机制,可以利用已有的数据类型来定义新的数据类型。
所定义的新的数据类型不仅拥有新定义的成员,而且还同时拥有旧的成员。
我们称已存在的用来派生新类的类为基类(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