为什么 C 的复杂类使用 getter 和 setter?
为什么C++复杂类使用函数来修改实部和虚部?公共成员变量在无需处理 getter 和 setter 的情况下是否也能正常工作?所隐藏的只是实部和虚部的私有名称。
Why does the C++ complex class use functions to modify the real and imaginary parts? Wouldn't public member variables work just as well without having to deal with getters and setters? All that's been hidden is the private name of the real and imaginary parts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原因很简单,它允许实现随着时间的推移而改变,即使它实际上可能不会经常改变(如果有的话)。如果您有一个类并且正在修改其实例变量,那么您现在依赖于现有的这些实例变量,而不是拥有一个可以保持不变而无需更改的公共接口(尽管实现发生了变化,例如使用依赖于平台的代码) )。
Femaref 的答案也是正确的——这些方法可以允许某些可能必要的逻辑发生。如果没有它,您可能无法从对象中获取正确的数据。
The simple reason for this is that it allows the implementation to change over time, even if it may not actually change often (if ever). If you have a class and you're modifying its instance variables, you're now dependent on those instance variables existing instead of having a public interface that could remain the same without changing (despite the implementation changing, for example with platform-dependent code).
Femaref's answer is also correct – the methods can allow for certain logic to occur that might be necessary. Without that, you might not be getting the correct data from the object.
可能是因为方法中有额外的逻辑,这是公共成员变量不可能实现的。
Probably because there is additional logic in the methods, which is not possible with public member variables.