c++ - 有没有办法在派生类中禁止基类方法调用?
问题描述
在 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() {}
};
解决方案
是否可以 [...] 禁止在派生类中调用基类方法?
是的。通过使用私有访问说明符。私有名称只能由类本身访问。
然而,这不是逆逻辑。不可能减少派生类对其他公共名称的可访问性。
推荐阅读
- python - tensorflow.python.framework.errors_impl.InternalError: Dst tensor is not initialized
- c# - 如何在 Xamarin.Forms 的 NavigationPage.SetTitleView 中调用 XAML 代码?
- html - HTML 页面上的表格使用的宽度比 div 大得多
- soapui - 如何将 JSON 选项卡设置为 SOAP UI Open Source 中响应的默认视图?
- arrays - ios swift4中的Paytm校验和不匹配
- api - Dialogflow api突然返回CORS错误
- c# - 为 Asp.net 项目集成 CkEditor 5
- matlab - 在matlab中从二进制图像中提取白色像素
- chatbot - 用于测试聊天机器人的 Botium Box 社区版
- android - 从图像选择器中裁剪的图像