可以嵌套 C++类继承其封闭类?
我正在尝试执行以下操作:
class Animal
{
class Bear : public Animal
{
// …
};
class Giraffe : public Animal
{
// …
};
};
...但我的编译器似乎对此感到窒息。这是合法的 C++ 吗?如果不是,是否有更好的方法来完成同样的事情?本质上,我想创建一个更清晰的类命名方案。 (我不想从公共基类派生 Animal
和内部类)
I’m trying to do the following:
class Animal
{
class Bear : public Animal
{
// …
};
class Giraffe : public Animal
{
// …
};
};
… but my compiler appears to choke on this. Is this legal C++, and if not, is there a better way to accomplish the same thing? Essentially, I want to create a cleaner class naming scheme. (I don’t want to derive Animal
and the inner classes from a common base class)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
“颠倒继承”的 ATL 方法总是值得考虑的。每次我需要这样做时都会让我头疼,但你得到的目标代码的效率是无与伦比的。我在某个地方剪下了吉姆·贝弗里奇(Jim Beveridge)的文章,这是我见过的最好的解释,但今天很难找到,我只看到对其的引用。
“2004 年 3 月 25 日……Jim Beveridge 的一篇优秀文章:ATL 和颠倒继承……”
It's always worth considering the ATL method of "Upside-Down Inheritance". It makes my head hurt every time I need to do this, but the efficiency of the object-code you get is unbeatable. Somewhere I clipped the article by Jim Beveridge which was the best explanation I ever saw, but this is hard to find today, I just see a reference to it.
"Mar 25, 2004 ... An excellent article from Jim Beveridge: ATL and Upside-Down Inheritance.."
你可以做你想做的事,但是你必须延迟嵌套类的定义。
You can do what you want, but you have to delay the definition of the nested classes.
在到达其定义末尾之前,类类型被视为不完整。您不能从不完整的类继承,因此您不能从封闭类继承。
编辑:更正
正如 Richard Wolf 纠正我的那样:如果延迟嵌套类的定义,则可以从封闭类继承。详情请参阅他的回答。
The class type is considered incomplete until the end of its definition is reached. You cannot inherit from incomplete class so you cannot inherit from enclosing class.
EDIT: Correction
As Richard Wolf corrected me: It is possible to inherit from enclosing class if you delay the definition of the nested classes. See his answer for details.
并没有真正回答这个问题,但我认为你滥用了嵌套类,也许你应该看看命名空间(顺便说一句,答案是“这是不可能的,因为 Animal 是一个不完整的类型”)。
Doesn't really answer the question, but I think you're misusing nested class, maybe you should have a look at namespaces (by the way, the answer is "it's not possible, because Animal is an incomplete type").
我不清楚你想在这里实现什么,但你也许可以通过名称空间获得它。
这将 Bear 和 Giraffe 声明为动物类型,但如果您正在寻找不污染全局名称空间的基类,则将整个事物放入名称空间中。
I'm not clear what you are trying to achieve here but you may be able to get it via namespaces.
This declares Bear and Giraffe as types of animals but puts the whole thing in a namespace if you are looking for the base class to not pollute the global namespace.