【发布时间】:2018-05-14 12:13:29
【问题描述】:
如何确保只有“我的”代码才能使用一个类,即使它使用了一个基类? (如果它不用作基类,我可以将其设为 private 或 protected 我的一个类的嵌套类)
如果我想表明对我的一个类使用基类仅仅是实现细节,我可以使用私有基类:
class Base
{
...
}
class Derived: private Base
{
public:
Derived(...): Base{...} {... };
...
}
对于我的Derived 类的客户,我使用Base 类并不明显:
#include "Derived.h"
void client() {
Derived d{...};
Base *b = static_cast< Base * >(&d);// error
...
}
但想象一下 Base 类是如此专业化、令人困惑或难以使用,以至于我不希望我的代码的客户可以将它用作基类或创建它的对象班级。在某种意义上,我希望它对我的某些代码是“私有的”,所以这样的客户端代码会失败:
#include "Derived.h"
class Client: Base// error wanted here
{
public:
Client(...): Base{...} {...};
...
}
void client()
{
Derived d{...};// OK
Base b{...};// error wanted here
Client c{...};// error wanted here
}
我该怎么做?
实际上,我在问如何实现Java's package-private classes 之类的东西,只有同一个“包”(模块)中的其他类可以访问,但不能被“包”之外的代码使用。
【问题讨论】:
标签: c++ inheritance private