首页 > 解决方案 > 有没有办法在派生类中禁止基类方法调用?

问题描述

在 c++ 中,“protected”修饰符只允许在派生类中调用方法。是否可以实现逆逻辑——禁止在派生类中调用基类方法?下面的代码说明了我想要得到的东西。

class Base
{
   int data;
protected:
   // This constructor should be called only in the derived classes
   Base(int d): data(d) { }
public:
   // This construcor can be called wherever except a derived classes!
   Base(): data(0) { }
};

class Derived : public Base
{
public:
   // The developer must not forget to initialize "data"
   Derived() : Base(10) {}

   // I want to get a compilation error there
   Derived() : Base() {}
};

标签: c++oop

解决方案


是否可以 [...] 禁止在派生类中调用基类方法?

是的。通过使用私有访问说明符。私有名称只能由类本身访问。

然而,这不是逆逻辑。不可能减少派生类对其他公共名称的可访问性。


推荐阅读