C++ 繼承

注:參考東南大學《C++程序設計教程》視頻,主講老師:何潔月。此內容爲自學時所記筆記
第七章   類的繼承與派生
繼承:保持已有類的特性而構成新類的過程  目的:實現代碼重用
派生:在已有類的基礎上新增自己的特性而產生新類的過程  目的:原程序進行改造嗎
      (1)吸收基類 。(2)改造 同名覆蓋。(3)新增加。
基類--->派生類
公有繼承:class B{};
          class A:public B{};
          派生類的“成員函數”可以訪問基類public ,protected。
          派生類的“對象”只能訪問基類的public。

例:
#include
using namespace std;
class Point
{
public :
  //  Point (float x,float y){X=x;Y=y;}
    void InitP(float x,float y){X=x;Y=y;}
    float getX(){return X;}
    float getY(){ return Y;}
    void Print();
    void Move(float x,float y);
private :
    float X,Y;
};
void Point::Move(float x,float y){
    X+=x;
    Y+=Y;
}
void Point::Print(){
      cout<<getX()<<" "<<getY()<<endl;
}
class Rectangle:public Point
{
public :
    void InitR(float x,float y,float w,float h){
        InitP(x,y);
        W=w;
        H=h;
    }
    float getW(){return W;}
    float getH(){return H;}
    //void Print();
private:
     float W,H;
};
int main()
{
     Rectangle r;
     r.InitR(1,1,1,1);
     r.Move(1,1);
     r.Print();
     return 0;
}

私有繼承:
    class B{};
    class A:private B{};
    public 和protected 成員以private 出現在派生類中,
    派生類的成員函數不能訪問基類的private成員。
    派生類的對象不能訪問任何成員,想要訪問,必須重新構造方法

 class Rectangle:private Point
{
public :
    void InitR(float x,float y,float w,float h){
        InitP(x,y);
        W=w;
        H=h;
    }
    void Move(float x,float y);   //重新構造
    void Print();                 //重新構造
    float getX(){return Point::getX();}
    float getW(){return W;}
    float getH(){return H;}
    //void Point::Print();
private:
     float W,H;
};
void Rectangle::Move(float x,float y){
   Point::Move(x,y);
}
void Rectangle::Print(){
    Point::Print();
    cout<<W<<"--"<<H<<endl;
}

保護繼承(protected)
     class B{};
     class A :protected B{};
     派生類的成員可以訪問基類的public,protected
     派生類的對象不能訪問基類的所有成員。

     特點與作用:派生類外不能訪問基類的protected成員 ,
                 派生類類內可以訪問基類的......。

例:
class A
{
public :
    void setA(int aa){a=aa;}
    int getA(){return a;}
protected :
    int a;
};
class B:protected A
{
public :
    int getB(){return b;}
    void changeA(){a=a*2;}   //派生類內可以對基類protected成員操作
    int getA(){A::getA();}
    void setA(int x){A::setA(x);}
private:
       int b;
};
#include
using namespace std;
int main()
{
    B b;
    b.setA(10);
    b.changeA();
    cout<<b.getA()<<endl;
}
總結:三種繼承,派生類的成員訪問是一樣的,派生類的對象訪問
      不一樣,
      派生類中的成員屬性,public->protected->private 變換
              public      protected   private
:public       public      protected   private
:protected  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章