从 C+++ 中的受保护类继承
假设我有以下声明:
class Over1
{
protected:
class Under1
{
};
};
我知道我可以执行以下操作:
class Over2 : public Over1
{
protected:
class Under2 : public Under1
{
};
};
但是有没有办法声明 Under2 而不声明 Over2?
由于您必须扩展 Over1 才能使用 Under1 的任何导数,这可能看起来很愚蠢,但在这种情况下可能有 30 种不同风格的 Under。 我可以:
- 将它们全部放入 Over1 中: 不 有吸引力,因为 Over2 可能只使用 其中 1 或 2 个
- 将它们分别放入 他们自己版本的 Over : Not 从此你将拥有吸引力 乘以继承几乎 同班。
- 寻找一种创造的方式 Under1 的孩子无需创建 Over1 的孩子
那么这可能吗?
谢谢。
Suppose I have the following declaration:
class Over1
{
protected:
class Under1
{
};
};
I know that I could do the following:
class Over2 : public Over1
{
protected:
class Under2 : public Under1
{
};
};
But is there a way to declare Under2 without Over2?
Since you would have to extend Over1 to use any derivative of Under1 this may seem silly, but in this situation there might be 30 different flavors of Under. I can either:
- Put them all inside Over1 : Not
attractive since Over2 may only use
1 or 2 of them - Put them each in
their own version of Over : Not
attractive since then you will have
to multiply inherit from almost the
same class. - Find a way to create
children of Under1 without creating
children of Over1
So is this possible?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
比创建嵌套类更好的是,您可能希望考虑将这些闭包嵌入到命名空间中。 这样,您就不需要外部类来获取内部类。 Google C++ 风格指南中有一些支持和反对的有力论据。
Better than creating nested classes, you might want to look at embedding those closses into a namespace. That way, you don't need the outer class in order to get the inner class. There are some great arguments for and against in the Google C++ Style Guide.
如果您想保护 Under1,那么根据定义,您需要继承 Over1 才能访问它。 我建议将 Under1 公开,或者按照 Douglas 的建议使用命名空间。
我现在没有编译器来测试这些,所以我完全不确定这些是否有效,但你可以尝试这个:
或者可能是这样的:
或者甚至:
虽然这会暴露所有 Over1s 私有到 Under2 - 不太可能是您想要的。
If you want to keep Under1 protected, then by definition, you need to inherit from Over1 to access it. I would suggest making Under1 public, or using namespaces as Douglas suggested.
I don't have the compiler to test these out right now, so I'm not at all sure that these would work, but you could try this:
Or perhaps something like this:
Or even:
Although that would expose all of Over1s privates to Under2 - not likely something you'd want.
对我来说听起来有点时髦的设计。 为什么不尝试以不同的方式构建代码呢? 我认为这可能是装饰器模式的一个很好的候选者,您可以将基类包装在各种装饰器中以实现所需的功能,“under”的各种风格都可以是装饰器。 只是一个想法,如果不了解更多代码的意图,很难说清楚。
Sounds like a bit of a funky design to me. Why not try structuring your code differently. I think this could possibly be a good candidate for the decorator pattern, where you could wrap your base class in various decorators to achieve the desired functionality, the various flavors of 'under' could be decorators. Just a thought, hard to tell without knowing more about the intentions of your code.
使用模板和显式特化,您只需在 Over1 中添加一个类声明即可完成此操作。
希望这可以帮助。
Using templates and explicit specializations you can do this with just one additional class declaration in Over1.
Hope this helps.