私有类数据

发布于 2024-09-25 08:16:14 字数 147 浏览 0 评论 0原文

您是否应该将类中除函数之外的所有数据保留在私有部分中?例如:我有一个 std::list 整数,我需要在其他类中访问它。您将如何迭代它并且您真的想将其保密吗?

编辑:

我正在寻找对其他类中每个元素的单独访问权限。

should you keep all the data except functions in your class in private section? for example: I have a std::list of integers which i need to access in other class. how would you iterate it and would you really want to keep it private?

Edit:

I'm looking for an individual access to each element in other class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雪化雨蝶 2024-10-02 08:16:14

真正的问题是为什么您需要迭代“其他类”中的列表。如果您需要在客户端类中执行特定操作,您可以有其他选择:

  1. 如果您需要执行明确定义的操作(例如,计算列表中值的平均值),那么您可以实现此功能作为保存列表的类的成员函数。

  2. 对列表执行各种操作,那么您可以构建一个通用迭代器接口,它接受实现各种操作并返回您需要的任何结果的函数或仿函数。

这些选项都不需要您公开列表本身。

The real question is why you need to iterate over the list in the 'other class'. If you need to perform a specific operation in the client class you could have other choices:

  1. If you need to perform a well-defined operation (say, computing an average of the values in the list) then you can implement this functionality as a member function of the class that keeps the list.

  2. If you need to perform all kinds of operations on the list then you can build a generic iterator interface, which accepts functions or functors that implement the various operations and return whatever results you need.

Neither of these options require you to expose the list itself.

北方的巷 2024-10-02 08:16:14

是的,我会将其保密,因为我不希望任何人修改它。然后提供一对 const_iterator 来迭代列表。

Yes, I would keep it private as I don't want anybody to modify it. Then provide a pair of const_iterators to iterate ovet the list.

一袭白衣梦中忆 2024-10-02 08:16:14

是的,我会保密。现在我们知道类的成员函数可以访问该类的私有成员,那么为什么不在成员函数本身中迭代 std::list 呢?

如果您需要在其他类中访问它,那么您需要创建前一个类的对象(通过调用该对象上的某些成员函数来执行插入活动等),然后调用将执行迭代活动的成员函数。

我错过了什么吗?

Yes I would keep it private. Now as we know member functions of a class can access private members of that class so why not iterate over the std::list in the member function itself?

If you need to access it in some other class then you need to create an object of the former class(perform the inserting activity etc by calling some member function on that object) and then call the member function which would perform the iteration activity.

Have I missed something?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文