簡體   English   中英

訪問孫類中受保護的基類成員

[英]Access protected members of base class in grandchild class

我有一個包含聲明為protected屬性的父類。 我知道可以在子類中訪問protected成員。 但是如何在孫子類中訪問相同內容。

例如,如何在TooSmall類中訪問width

考慮以下代碼示例:

#include <iostream>
using namespace std;

class Box {
   protected:
      double width;
};

class SmallBox:Box {
   protected:
      double height;
};

class TooSmall:SmallBox {
    public:
        void setSmallWidth( double wid );
        void setHeight(double hei);
        double getSmallWidth( void );
        double getHeight(void);
};


double TooSmall::getSmallWidth(void) {
   return width ;
}

void TooSmall::setSmallWidth( double wid ) {
   width = wid;
}

void TooSmall::setHeight( double hei ) {
   height = hei;
}

double TooSmall::getHeight(void) {
   return height;
}

// Main function for the program
int main() {
   TooSmall box;

   box.setSmallWidth(5.0);
   box.setHeight(4.0);
   cout << "Width of box : "<< box.getSmallWidth() << endl;
   cout << "Height of box : "<< box.getHeight() << endl;

   return 0;
}

有沒有一種方法可以使子類中的父類屬性public

您的問題是您是從基類私有繼承的,因此基類的公共成員和受保護成員與派生類的私有成員具有相同的訪問控制。 盡管可能,私有繼承是一個非常特定的工具,很少使用。 在大多數情況下,您需要公共繼承:

class SmallBox: public Box {
   protected:
      double height;
};

class TooSmall: public SmallBox {
    public:
        void setSmallWidth( double wid );
        void setHeight(double hei);
        double getSmallWidth( void );
        double getHeight(void);
};

這樣,受保護的成員將對所有后代(不僅是直系子代)正常可見。


如果出於某種原因,您想堅持私有繼承,則必須將私有繼承的受保護成員“提升”為protected:

class SmallBox:Box {
   protected:
      double height;
      using Box::width; // make it protected again
};

class TooSmall:SmallBox {
    public:
        void setSmallWidth( double wid );
        void setHeight(double hei);
        double getSmallWidth( void );
        double getHeight(void);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM