开发者

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

开发者 https://www.devze.com 2023-01-05 16:00 出处:网络
I would like to combine setter/getter in one method, in C++, in order to be able to do the following:

I would like to combine setter/getter in one method, in C++, in order to be able to do the following:

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:

class Foo {
public:
  // how to set default value??
  const string& name(const string& n /* = ??? */) {
    if (false /* is it 开发者_StackOverflow中文版a new value? */) {
      _name = n;
    }
    return _name;
  }
private:
  string _name;
}

I'm looking for some elegant solution, with a true C++ spirit :) Thanks!


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 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. This would work, but it would totally break when someone has a const Foo and wants to execute GetA(). For that reason, I advise separate functions and a const GetA().

class Foo
{
   int _a;
   static int _null;
public:
   const int& a(const int& value = _null) {
      if (&value != &_null)
         _a = value;

      return _a;
   }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消