问题描述
我已经在C#编程了一段时间,现在我想刷新我的C ++技能。
I have been programming in C# for a while and now I want to brush up on my C++ skills.
拥有类:
class Foo
{
const std::string& name_;
...
};
什么是最好的方法(我只想允许读取访问name_字段):
What would be the best approach (I only want to allow read access to the name_ field):
- 使用getter方法:
inline const std :: string& name()const {return name_; }
感谢。
推荐答案
将非const字段公开是一个坏主意,因为它很难强制错误检查
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.
在你的情况下,你有一个const字段,所以上面的问题不是问题。使它成为公共领域的主要缺点是,你锁定了底层的实现。例如,如果将来你想将内部表示更改为C字符串或Unicode字符串,或其他,那么你会破坏所有的客户端代码。使用gettor,您可以转换为现有客户的旧版表示,同时通过新的gettor为新用户提供更新的功能。
In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a gettor, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new gettor.
我仍然建议使用getter方法就像你放置在上面。这将最大限度地提高您未来的灵活性。
I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.
这篇关于C ++ getters / setters编码风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!