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.