简体   繁体   English

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

[英]Can I combine setter and getter in one method, in C++?

I would like to combine setter/getter in one method, in C++, in order to be able to do the following: 我想在一个方法中用C ++组合setter / getter,以便能够执行以下操作:

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

I don't know how can I declare such a method inside Foo class: 我不知道如何在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;
}

I'm looking for some elegant solution, with a true C++ spirit :) Thanks! 我正在寻找一些优雅的解决方案,具有真正的C ++精神:)谢谢!

class Foo {
public:

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

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

private:
  string name_;
};

You can create a second method with different parameters, in this case none to simulate a default parameter: 您可以使用不同的参数创建第二个方法,在这种情况下,无法模拟默认参数:

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;
}

And if you need a const getter, just add it as well! 如果你需要一个const getter,也可以添加它!

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

The compiler will know which one to call, that's the magic of overloading. 编译器将知道要调用哪一个,这是重载的神奇之处。

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.

I would not advise trying to do this, because then you can't make your "get" functions const. 我不建议尝试这样做,因为那时你不能使你的“获取”函数const。 This would work, but it would totally break when someone has a const Foo and wants to execute GetA(). 这可以工作,但是当有人拥有const Foo并且想要执行GetA()时它会完全破坏。 For that reason, I advise separate functions and a const 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM