我可以在一个方法中用C ++组合setter和getter吗?

时间:2010-07-06 05:21:41

标签: c++

我想在一个方法中用C ++组合setter / getter,以便能够执行以下操作:

Foo f;
f.name("Smith");
BOOST_CHECK_EQUAL("Smith", f.name());

我不知道如何在Foo class:

中声明这样的方法
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 ++精神:)谢谢!

3 个答案:

答案 0 :(得分:6)

class Foo {
public:

  const string& name() const {
    return name_;
  }

  void name(const string& value) {
    name_ = value;
  }

private:
  string name_;
};

答案 1 :(得分:3)

您可以使用不同的参数创建第二个方法,在这种情况下,无法模拟默认参数:

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.

答案 2 :(得分:1)

我不建议尝试这样做,因为那样你就不能使你的“获取”函数成为常量。这可以工作,但是当有人拥有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;
   }
};
相关问题