继承和派生是C++与C不同的重要特征之一。
继承:保持已有类的特性而构造新类的过程。意义为子类继承了父类中public和protected属性的成员,同时又有自己特征的一些成员。
派生:在已有类的基础上新增自己的特性而产生新类的过程。
增加继承和派生能够实现代码重用,减少工作量。
继承规则:基类或父类中的public和protected成员被继承,而private成员不能被继承。
三种继承方式:
公有继承:继承过来的public和protected成员全部变成public类型的成员,派生类中的成员函数可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员。通过派生类的对象只能访问公有继承的public成员。
私有继承:继承过来的public和protected成员全部变成private类型的成员,派生类中的成员函数可以直接访问基类中的public和protected成员,不能访问基类的private成员。通过派生来的对象不能直接访问基类中的任何成员。
保护继承:继承过来的public和protected成员全部变成protected类型的成员,派生类中的成员函数可以直接访问基类中的public和protected成员,但不能访问基类的private成员,通过派生类的对象不能直接访问基类中的任何成员。
不同继承方式的影响主要体现在派生类成员或对象对基类成员的访问权限。
类型兼容规则:
(1):一个公有派生类的对象在使用上可以被当作基类的对象,反之则禁止
(2):指向基类的指针也可以指向派生类,但只能使用从基类继承的成员。
#include <iostream>
using namespace std;
class B0 //基类B0的生命
{
public:
void display()
{
cout << "B0::display" << endl;
}
};
class B1:public B0 //B1从B0公有继承
{
public:
void display()
{
cout << "B1::display" << endl;
}
};
class D1 :public B1
{
public:
void display()
{
cout << "D1::display" << endl;
}
};
void fun(B0 *ptr)
{
ptr->display();
}
int main(void)
{
//声明对象及指针
B0 b0;
B1 b1;
D1 d1;
B0 *p;
//指向基类的指针也可以指向派生类
//但只能使用从基类继承的成员
p = &b0;
fun(p);
p = &b1;
fun(p);
p = &d1;
fun(p);
return 0;
}
运行结果如图所示:
基类与派生类的对应关系:
单继承:派生类只从一个基类派生
多继承:派生类从多个基类派生
多重派生:由一个基类派生出多个不同的派生类
多层派生:派生类又作为基类,继续派生新的类。
继承时的构造函数:
(1):基类的构造函数不被继承,派生类中需要声明自己的构造函数。
(2):声明构造函数时,只需要对本类中新增成员进行初始化,对继承来的基类成员的初始化自动调用基类构造函数完成
(3):派生类的构造函数需要给基类的构造函数传递参数
参考源代码如下:
#include <iostream>
using namespace std;
class Point //基类Point的声明
{
public:
void InitPoint(float xx = 0, float yy = 0)
/*将函数体写在类的成员函数的声明中形成内联函数*/
{
X = xx;
Y = yy;
}
void Move(float xOff, float yOff)
{
X += xOff;
Y += yOff;
}
float GetX()
{
return X;
}
float GetY()
{
return Y;
}
private:
float X, Y;
};
/*派生类Rectangle的声明*/
class Rectangle :public Point //Rectangle由Point继承而来
{
/*派生类中的成员函数可以直接访问基类中的public和proteccted成员,
但是不能直接访问基类中的private成员*/
/*新增共有函数成员*/
public:
void InitRectangle(float x, float y, float w, float h)
{
InitPoint(x, y); //调用基类共有成员函数
W = w;
H = h;
}
float GetH()
{
return H;
}
float GetW()
{
return W;
}
/*新增私有数据成员*/
private:
float W, H;
};
int main(void)
{
Rectangle rect; //声明一个类型为Rectangle的对象rect
/*派生类中的对象只能访问基类中的public成员函数*/
rect.InitRectangle(2, 3, 20, 10);
rect.Move(3, 2);
cout << rect.GetX() << ", "
<< rect.GetY() << ", "
<< rect.GetH() << ", "
<< rect.GetW() << endl;
return 0;
}
代码无实际意义,纯属为功能验证。