问题描述
有人可以指点我一些很好的资源来理解和使用嵌套类吗?我有一些像编程原则这样的材料 IBM 知识中心 - 嵌套类
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(nullptr), tail(nullptr) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
在这里,我不想公开 Node,因为其他人可能决定使用该类,这会妨碍我更新我的类,因为公开的任何内容都是公共 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++ 中使用嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!