为什么要在C ++中使用嵌套类? [英] Why would one use nested classes in C++?

查看:124
本文介绍了为什么要在C ++中使用嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我一些不错的资源来理解和使用嵌套类吗?我有一些材料,如编程原则和这样

Can someone please point me towards some nice resources for understanding and using nested classes? I have some material like Programming Principles and things like this IBM Knowledge Center - Nested Classes

但我仍然无法了解他们的目的。

But I'm still having trouble understanding their purpose. Could someone please help me?

推荐答案

嵌套类非常适合隐藏实现细节

Nested classes are cool for hiding implementation details

列表:

class List
{
    public:
        List(): head(NULL), tail(NULL) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

这里我不想公开Node,因为其他人可能决定使用类,阻止我更新我的类,因为任何公开的API是公共API的一部分,必须保持永远。通过使类私有,我不仅隐藏的实现,我也说这是我的,我可以随时更改它,所以你不能使用它。

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

查看在std :: list或std :: map他们都包含隐藏类(或者他们?)。关键是他们可能或可能不会,但是因为实现是私有的和隐藏的STL的构建者能够更新代码,而不影响你如何使用代码,或者留下很多旧行李围绕STL,因为他们需要以保持与一些愚蠢人的向后兼容性,他们决定要使用隐藏在< list>中的Node类。

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside <list>.

这篇关于为什么要在C ++中使用嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆