以下据说比公共成员有第一个/第二个更好.我相信这几乎一样糟糕.如果您正在提供一种方法来访问课外的私有变量,那么重点是什么?功能不应该是
T First(); void(or T) First(const T&)
Run Code Online (Sandbox Code Playgroud)
样品:
// Example 17-3(b): Proper encapsulation, initially with inline accessors. Later
// in life, these might grow into nontrivial functions if needed; if not, then not.
//
template<class T, class U>
class Couple {
Couple() : deleted_(false) { }
T& First() { return first_; }
U& Second() { return second_; }
void MarkDeleted() { deleted_ = true; }
bool IsDeleted() { return deleted_; }
private:
T first_;
U second_;
bool deleted_;
};
Run Code Online (Sandbox Code Playgroud) 所以我有一些相当广泛的功能代码,主要数据类型是不可变的结构/类.通过制作成员变量和任何方法const,我一直在声明不变性的方式是"几乎不可变的".
struct RockSolid {
const float x;
const float y;
float MakeHarderConcrete() const { return x + y; }
}
Run Code Online (Sandbox Code Playgroud)
这实际上是C++中"我们应该这样做"的方式吗?或者,还有更好的方法?
c++ functional-programming const-correctness immutability c++11