继承与派生
继承与派生的层次结构是将各对象进行具体化,特殊化,然后将它们关系抽象化的过程。
继承就是从先辈处得到属性和行为特征。而类的继承是新的类从已有类那得到已有的特征。由此可知,从已有类产生的新类的过程就是类的派生。类的继承与派生,其机制决定了会进行数据的共享,同时就会导致数据安全性降低,因此它的作用主要是对已有类进行更具体详细地修改和扩充。
由原有类(基类或父类)产生的新类(派生类或子类),它会包含原有类的特征(体现继承的特点),同时也可加入自己所特有的新特点。派生类也可作为基类继续派生出子类,这样通过类的派生建立具有相同关键特征的对象家族可实现代码的重用,这种机制有利于对已有程序进行改进和发展。
派生类的定义或声明:
class 派生类名: 继承方式 基类名1,继承方式 基类名2,``````````继承方式 基类名n
- 1,派生类可继承于多个基类,同理也可继承于1个基类,即为多继承和单继承
- 2,继承方式:公有继承,私有继承,保护继承。3中继承方式主要是派生类在基类中的数据访问权限有区别。
① 公有继承:基类的成员在派生类中保持原有的访问权限。
public,protected在派生类中可直接使用,private不可直接使用(若需要使用,可在基类的public中设置
接 口,属于间接使用)。
#include<iostream> using namespace std; class point { private: float x, y; public: void move(float xOFF, float yOFF) {x += xOFF; y += yOFF;} void initP(float x = 0, float y = 0) { this->x = x; this->y = y; } float getx() {return x;} float gety() {return y;} }; class Rectangle :public point //定义公有继承的派生类 { private: float w, h; public: void initR(float x, float y, float w, float h) { initP(x,y); //直接调用基类的共有成员函数 this->w = w; this->h = h; } float getw() {return w;} float geth() {return h;} }; int main() { Rectangle rect; rect.initR(2, 3, 20, 10); cout<<"未移动之前的坐标:("; cout << rect.getx() << ","; cout << rect.gety() << ","; cout << rect.getw() << ","; cout << rect.geth() <<")"<<endl; rect.move(3, 2); cout<<"x移动3,y移动2"<<endl; cout << "移动之后的坐标(:" ; cout << rect.getx() << ","; cout << rect.gety() << ","; cout << rect.getw() << ","; cout << rect.geth() <<")"<<endl; return 0; }
② 私有继承:基类的public,protected成员都以private身份出现在派生类中,即为派生类的私有成员(通过派生类的外部访问基类的公有成员是做不到的),不能直接使用, 采用"函数调用"的方式。 **派生类的成员函数**可以直接访问基类的public和protected成员,但不能直接访问private成员; **派生类对象**不能直接访问基类的所有成员。
#include<iostream> using namespace std; class point { private: float x, y; public: void move(float xOFF, float yOFF) {x += xOFF; y += yOFF;} void initP(float x = 0, float y = 0) { this->x = x; this->y = y; } float getx() {return x;} float gety() {return y;} }; class Rectangle :private point //定义私有继承的派生类 { private: float w, h; public: void initR(float x, float y, float w, float h) { initP(x,y); this->w = w; this->h = h; } void mov(float xOFF, float yOFF) { move(xOFF, yOFF); } float gtx() { return getx(); } float gty() { return gety(); } //Rectangle的成员函数void mov(),float gtx()与float gty() 可直接访问基类的成员函数 float getw() {return w;} float geth() {return h;} }; int main() { Rectangle rect; rect.initR(2, 3, 20, 10); cout << "未移动之前的坐标:("; cout << rect.gtx() << ","; cout << rect.gty() << ","; cout << rect.getw() << ","; cout << rect.geth() <<")"<< endl; rect.move(3, 2); cout << "x移动3,y移动2" << endl; cout << "移动后坐标:(" ; cout << rect.gtx() << ","; cout << rect.gty() << ","; cout << rect.getw() << ","; cout << rect.geth() <<")"<<endl; return 0; }
③ 保护继承:基类的public,protected成员以protected的身份出现在基类中,派生类成员可直接访问继承的public和 protected成员,基类的私有成员不可直接访问。同样,通过派生类的外部,访问基类的公有成员也是做不到的。