三種繼承方式

2021-08-20 21:16:09 字數 1942 閱讀 1474

三種繼承方式:公有繼承

,私有繼承,保護繼承

不同繼承方式的影響主要體現在:

公有繼承:

//標頭檔案部分

#ifndef_point_h

#define _point_h

class point

void move(int offx, int offy)

int getx() const

int gety() const

private:                                    //私有資料成員

int x, y;

};#endif                                      //_point_h

#ifndef_rectangle_h

#define _rectangle_h

#include "point.h"

class rectangle : public point

int geth() const

int getw() const

private:                                    //新增私有資料成員

int w, h;

};#endif                                      //_rectangle_h

//程式主函式

#include #include using namespace std;

int main()

程式執行結果

the data of rect(x, y, w, h) :

5,5,20,20

私有繼承(private)

#ifndef_point_h

#define _point_h

class point

void move(float offx, float offy)

int getx() const

int gety() const

private:                                            //私有資料成員

int x, y;

};#endif                                              //_point_h

#ifndef_rectangle_h

#define _rectangle_h

#include "point.h"

class rectangle : private point

void move(int offx, int offy)

int getx() const

int gety() const

int geth() const

int getw() const

private:                                            //新增私有資料成員

int w, h;

};#endif                                              //_rectangle_h

#include #include using namespace std;

int main()

保護繼承(protected)

protected 成員的特點與作用:

class a ;

int main()

class a ;

class b : public a;

void b : function()

三種繼承方式

派生類繼承了基類的全部資料成員和除了建構函式,析構函式之外的全部資料成員,但是這些成員的訪問屬性在派生的過程中是可以調整的。從基類繼承的成員,其訪問屬性由繼承方式控制。類的公有繼承 當繼承方式為公有繼承時,基類的公有成員和保護成員的訪問屬性在派生類中不變,而基類的私有成員不可直接訪問。類的私有繼承 ...

三種繼承方式

原型鏈繼承 子類.prototype new 父類 引數 優點 繼承所有 繼承父類 本身 以及 原型物件上的所有 屬性 方法。缺點 不能給父類 的建構函式傳引數 function fu name fu.prototype.say function zi類 開始 function zi zi.prot...

三種繼承方式

1 公有繼承 基類的public成員被繼承到派生類的public訪問限定符下,基類的protected成員被繼承到派生類 的protected訪問限定符下,而基類的private成員被繼承到派生類的不可見位置,無法直接訪問。2 保護繼承 基類的protected成員和public成員都被繼承到派生類...