C++ 中的 Getter 和 Setter
我应该在 C++ 中使用 getter 和 setter 还是直接访问类数据更好?
Should I use getters and setters in C++ or is it better to access class data directly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
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.
这取决于您的实现是什么以及您想要什么风格。语言设计的一部分是能够使用封装,因此使用
get
和set
方法来访问类的私有数据通常是一个很好的做法。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
andset
methods to access the private data of a class.一般来说,吸气剂和吸气剂二传手更好。
例外情况是,如果您有一个简单的类(通常意味着没有成员函数),它只是用于将数据捆绑在一起,以便更容易地传递。
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.
如果 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.