类的继承与派生
继承与派生是同一过程从不同角度来看:
继承是保持原有类的特性的从而构造新的类;
派生是在原有类的基础上发展新的特性而构造新的类。
通常情况下,派生更多。
1. 继承的语法
- 单继承
//Derived是派生类名字,public代表继承方式,Base就是继承的基类
class Dreived : public Base {
//members
};
- 多继承
//Derived是派生类名字,Base1以public方式继承,Base2以private方式继承
class Derived : public Base1, private Base2 {
//menbers
};
2. 继承方式
类的继承方式主要影响以下两方面:
1. 在类的外部,派生类中从基类继承的成员的访问控制
2. 在类的内部,通过派生类成员和派生类对象对基类成员的访问权限
c++中有public、private和protected三种继承方式。
2.1 公有继承public
- 访问控制
基类中的成员在派生类中的访问权限不变 - 访问权限
派生类的成员函数可以直接访问基类中的public和protected成员,但不能直访问基类的private成员;
通过派生类的对象只能访问基类的public成员
2.2 私有继承private
- 访问控制
基类中的成员在派生类中的访问权限都变为private - 访问权限
派生类的成员函数可以直接访问基类中的public和protected成员,但不能直访问基类的private成员;
通过派生类的对象不能访问基类的任何成员(都变成private了当然不行)
2.3 保护继承protected
- 访问控制
基类中的public成员在派生类中的访问权限变为protected,其他不变 - 访问权限
派生类的成员函数可以直接访问基类中的public和protected成员,但不能直访问基类的private成员;
通过派生类的对象不能访问基类的任何成员(protected也是不能访问的呀)
我们通过以下的例子来看一下这三种继承方式的联系和区别:
#include <iostream>
#include<string>
using namespace std;
class Base1 {
public:
//继承后都是public
void initBase1(int x) {this -> x = x;};
int getX() { return this -> x;};
int getXX() { return this -> xx;};
protected:
//继承后都是protected
int xx;
private:
//继承后都是private
int x;
};
class Base2 {
public:
//继承后都是private
void initBase2(int y) {this -> y = y;}
int getY() { return this -> y;}
int getYY() { return this -> yy;}
protected:
//继承后都是private
int yy;
private:
//继承后都是private
int y;
};
class Base3 {
public:
//继承后都是protected
void initBase3(int z) {this -> z = z;}
int getZ() { return this -> z;}
int getZZ() { return this -> zz;}
protected:
//继承后都是protected
int zz;
private:
//继承后都是private
int z;
};
class Derived: public Base1, private Base2, protected Base3 {
public:
void initDerived(int x, int xx, int y, int yy, int z, int zz) {
//x是public-private的,不能直接被成员访问
//但initBase1是public-public的,可以直接被成员访问
initBase1(x);
//xx是public-protected的,可以被成员访问
this -> xx = xx;
//y是private-private的,不能直接被成员访问
//initBase和yy都是private-public的,可以被成员直接访问
initBase2(y);
this -> yy = yy;
//z是proteced-private的,不能直接被成员访问
//initBase3是protected-public的,可以直接被成员访问
initBase3(z);
//zz是protected-protected的,可以直接被成员访问
this -> zz = zz;
}
//getY在派生类中是private的,不能被对象访问,通过调用基类中public的getY访问y
int getYDerived() {return getY();}
//此处getYY是对基类中getYY的函数覆盖,其中调用了基类中的getYY
int getYY() { return Base2::getYY();}
//z是protected-private的,必须通过基类的成员来访问
int getZ() { return Base3::getZ();}
//zz是protected-protected的,也必须通过基类成员来访问
int getZZDerived() { return getZZ();}
};
int main() {
Derived d;
d.initDerived(1, 2, 3, 4, 5, 6);
//getX是public-public的,可以通过派生类对象访问,类似的还有getXX
cout << d.getX()<< endl;
cout << d.getXX()<< endl;
//getYDerived是public的,可以通过派生类对象访问
cout << d.getYDerived()<< endl;
//由于派生类覆盖了基类中的getYY,此处可以直接调用派生类的getYY
cout << d.getYY()<< endl;
cout << d.getZ() << endl;
cout << d.getZZDerived() << endl;
return 0;
}