继承

匿名 (未验证) 提交于 2019-12-03 00:14:01

继承方式规定了如何访问从基类继承的成员。

继承关键字为:public,protected和private。如果不显示地给出继承方式关键字,系统的默认值就认为是私有继承。

类的继承方式指定了派生类成员以及类外对象对于从基类继承来的成员的访问权限。

例子:

#include<iostream> using namespace std;  class Point { public:     void initPoint(float x = 0, float y = 0) {         this->x = x;         this->y = y;     }     void move(float offX, float offY) {         x += offX;         y += offY;     }     float getX() {         return x;     }     float getY() {         return y;     } private:     float x, y; };  class Rectangle :public Point { private:     float w, h; public:     void initRectangle(float x, float y, float w, float h)     {         initPoint(x, y);         this->w = w;         this->h = h;     }     float getH() { return h; }     float getW() { return w; } };  int main() {     Rectangle r;     r.initRectangle(2, 3, 20, 10);     r.move(3, 2);     cout << "The data of r(x,y,w,h):" << endl;     cout << r.getX() << "," << r.getY() << "," << r.getW() << "," << r.getH() << endl;      return 0; }

基类的public和protected成员可以直接访问,但是基类的private成员,不可直接访问。

如果在主函数中输入 r.a 就会出问题

当类的继承方式为私有继承时,基类中的公有成员和保护成员都以私有成员身份出现在派生类中,而基类的私有成员在派生类中不可直接访问。
这里的例子大致与上面相同,只是在第二个类中重新声明了一些函数。

    void move(float offX, float offY) { Point::move(offX, offY); }     float getX()  { return Point::getX(); }     float getY() { return Point::getY(); }

在私有继承情况下,为了保证基类的一部分外接接口特征能够在派生类中也存在,就必须在派生类中重新声明同名的成员。

保护继承中,基类的公有成员和保护成员都以保护成员身份出现在派生类中,而基类的私有成员不可直接访问。

其和公有继承有些区别

#include<iostream> using namespace std;  class A { protected:     int x; }; class B :protected A { public:     void c() { cout << "。。。" << endl; } };  int main() {     B a;     a.x; }

那么会报错

在需要基类对象的任何地方,都可以使用公有派生类的对象来替代。通过公有继承,派生类得到了基类中除构造函数,析构函数之外的所有成员。

派生类的对象可以隐含转换为基类对象。
派生类的对象可以初始化基类的引用。
派生类的指针可以隐含转换为基类的指针。

1.不管何种继承都不可以访问private成员。
2.派生类只可访问基类公有成员,其他则不可以访问。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!