[英]Can I combine setter and getter in one method, in C++?
我想在一個方法中用C ++組合setter / getter,以便能夠執行以下操作:
Foo f;
f.name("Smith");
BOOST_CHECK_EQUAL("Smith", f.name());
我不知道如何在Foo
類中聲明這樣的方法:
class Foo {
public:
// how to set default value??
const string& name(const string& n /* = ??? */) {
if (false /* is it a new value? */) {
_name = n;
}
return _name;
}
private:
string _name;
}
我正在尋找一些優雅的解決方案,具有真正的C ++精神:)謝謝!
class Foo {
public:
const string& name() const {
return name_;
}
void name(const string& value) {
name_ = value;
}
private:
string name_;
};
您可以使用不同的參數創建第二個方法,在這種情況下,無法模擬默認參數:
string& name() {
// This may be bad design as it makes it difficult to maintain an invariant if needed...
// h/t Matthieu M., give him +1 below.
return _name;
}
如果你需要一個const getter,也可以添加它!
const string& name() const {
return _name;
}
編譯器將知道要調用哪一個,這是重載的神奇之處。
Foo f;
f.name("Smith"); // Calls setter.
BOOST_CHECK_EQUAL("Smith", f.name()); // Calls non-const getter.
const Foo cf;
BOOST_CHECK_EQUAL("", cf.name()); // Calls const getter.
我不建議嘗試這樣做,因為那時你不能使你的“獲取”函數const。 這可以工作,但是當有人擁有const Foo並且想要執行GetA()時它會完全破壞。 出於這個原因,我建議使用單獨的函數和const GetA()。
class Foo
{
int _a;
static int _null;
public:
const int& a(const int& value = _null) {
if (&value != &_null)
_a = value;
return _a;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.