我用 C# 编程已经有一段时间了,现在我想复习一下我的 C++ 技能。
上课:
class Foo
{
const std::string& name_;
...
};
最好的方法是什么(我只想允许读取 name_ 字段):
- 使用getter方法:
inline const std::string& name() const { return name_; }
- 公开该字段,因为它是一个常量
谢谢。
最佳答案
对于长期存在的类来说,使用 getter 方法是更好的设计选择,因为它允许您在将来用更复杂的方法替换 getter 方法。尽管对于 const 值似乎不太可能需要此操作,但成本低且可能带来的好处很大。
顺便说一句,在 C++ 中,为成员同名的 getter 和 setter 是一个特别好的主意,因为将来您可以实际更改这对方法:
class Foo {
public:
std::string const& name() const; // Getter
void name(std::string const& newName); // Setter
...
};
到为每个定义一个 operator()()
的单个公共(public)成员变量中:
// This class encapsulates a fancier type of name
class fancy_name {
public:
// Getter
std::string const& operator()() const {
return _compute_fancy_name(); // Does some internal work
}
// Setter
void operator()(std::string const& newName) {
_set_fancy_name(newName); // Does some internal work
}
...
};
class Foo {
public:
fancy_name name;
...
};
客户端代码当然需要重新编译,但不需要更改语法!显然,这种转换同样适用于 const 值,其中只需要一个 getter。
关于C++ getter/setter 编码风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/760777/