C++中,當派生類方法的訪問許可權更嚴格時會發生什麼?


在本節中,我們將討論 C++ 中派生類方法訪問許可權限制的有趣事實。我們將看一些例子並分析輸出,以瞭解更多關於在 C++ 中使用派生類方法的限制。

示例 (C++)

讓我們看下面的實現來更好地理解:

#include <iostream>
using namespace std;
class BaseClass {
public:
   virtual void display(){
      cout << "Print function from the base class" << endl;
   }
};
class DerivedClass: public BaseClass {
private:
   void display() {
      cout << "Print function from the derived class" << endl;
   }
};
int main() {
}

這很好,現在如果我們用這個替換主函式塊,我們將得到如下錯誤:

int main() {
   DerivedClass d;
   d.display();
}

輸出

main.cpp: In function ‘int main()’:
main.cpp:20:15: error: ‘virtual void DerivedClass::display()’ is private
within this context
d.display();
^
main.cpp:13:10: note: declared private here
void display() {
^~~~~~~

它顯示一個錯誤,因為派生類中的方法是私有的。現在讓我們看這個實現,其中函式是使用基指標呼叫的。這可以呼叫函式。

示例 (C++)

線上演示

#include <iostream>
using namespace std;
class BaseClass {
public:
   virtual void display(){
      cout << "Print function from the base class" << endl;
   }
};
class DerivedClass: public BaseClass {
private:
   void display() {
      cout << "Print function from the derived class" << endl;
   }
};
int main() {
   BaseClass *b = new DerivedClass;
   b->display();
}

輸出

Print function from the derived class

從上面的程式可以看出,私有函式 `DerivedClass::display()` 是透過基類指標呼叫的,程式執行正常,因為 `display()` 函式在基類中是公有的。訪問說明符在編譯時進行驗證,`display()` 在基類中是公有的。在執行時,只調用與指向的物件對應的函式,並且不驗證訪問說明符。因此,派生類的私有函式可以透過基類指標呼叫。

更新於:2020年8月27日

78 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.