C++ 中的 Getter 和 Setter

发布于 2024-09-12 01:02:24 字数 48 浏览 4 评论 0原文

我应该在 C++ 中使用 getter 和 setter 还是直接访问类数据更好?

Should I use getters and setters in C++ or is it better to access class data directly?

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

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

发布评论

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

评论(4

青丝拂面 2024-09-19 01:02:24

getter 和 setter 的通常原理是:您可以将其从私有字段的简单包装器更改为相当复杂的计算,而无需使用该类破坏任何代码。如果您确定 getter/setter 永远不会超过这个数量(或者永远不会使用那么多),请随意使用公共字段,我不介意。

The usual rationale for getters and setters is: You can change it from being a simple wrapper around a private field to a rather complex computation without breaking any code using the class. If you're sure the getters/setter will never be more than that (or it will never be used that much), feel free to use a pulic field, I don't mind.

停顿的约定 2024-09-19 01:02:24

这取决于您的实现是什么以及您想要什么风格。语言设计的一部分是能够使用封装,因此使用 getset 方法来访问类的私有数据通常是一个很好的做法。

It depends what your implementation is and what style you are going for. Part of the language design is to be able to use encapsulation so it would generally be good practice to use get and set methods to access the private data of a class.

℡Ms空城旧梦 2024-09-19 01:02:24

一般来说,吸气剂和吸气剂二传手更好。

例外情况是,如果您有一个简单的类(通常意味着没有成员函数),它只是用于将数据捆绑在一起,以便更容易地传递。

In general, getter & setter are better.

The exception is if you have a simple class -- generally meaning one without member functions -- which is just used to bundle data together so it can be passed around easier.

撩人痒 2024-09-19 01:02:24

如果 getter/setter 中除了从公共字段返回/分配值之外没有任何逻辑,那么使用 getter/setter 和直接访问该字段之间没有显着差异。

If there's no logic in getter/setter except for returning/assigning a value from/to a public field there's no significant difference between usage of getters/setters and accessing the field directly.

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