gpt4 book ai didi

c++ - 简单的 C++ getter/setter

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:44 24 4
gpt4 key购买 nike

最近我将我的 getter 和 setter 编写为(注意:真正的类在 getter/setter 中做更多的事情):

struct A {
const int& value() const { return value_; } // getter
int& value() { return value_; } // getter/setter
private:
int value_;
};

它允许我执行以下操作:

auto a = A{2}; // non-const object a

// create copies by "default" (value always returns a ref!):
int b = a.value(); // b = 2, is a copy of value :)
auto c = a.value(); // c = 2, is a copy of value :)

// create references explicitly:
auto& d = a.value(); // d is a ref to a.value_ :)
decltype(a.value()) e = a.value(); // e is a ref to a.value_ :)
a.value() = 3; // sets a.value_ = 3 :)

cout << b << " " << c << " " << d << " " << e << endl; // 2 2 3 3

const auto ca = A{1};
const auto& f = ca.value(); // f is a const ref to ca.value_ :)
auto& g = ca.value(); // no compiler error! :(
// g = 4; // compiler error :)
decltype(ca.value()) h = ca.value(); // h is a const ref to ca.value_ :)
//ca.value() = 2; // compiler error! :)

cout << f << " " << g << " " << h << endl; // 1 1 1

这种方法不允许我:

  • 验证 setter 的输入(这是一个很大的 BUT),
  • 在 const 成员函数中按值返回(因为我希望编译器捕获对 const 对象的赋值:ca.value() = 2)。更新:请参阅下面的 cluracan 答案。

但是,我仍然经常使用它,因为

  • 大多数时候我不需要,
  • 这使我能够将我的类的实现细节与其接口(interface)分离,这正是我想要的。

例子:

struct A {
const int& value(const std::size_t i) const { return values_[i]; }
int& value(const std::size_t i) { return values_[i]; }
private:
std::vector<int> values_;
// Storing the values in a vector/list/etc is an implementation detail.
// - I can validate the index, but not the value :(
// - I can change the type of values, without affecting clients :)
};

现在回答问题:

  • 这种方法还有其他我没有看到的缺点吗?
  • 人们为什么喜欢:
    • 具有不同名称的 getter/setter 方法?
    • 将值作为参数传递?只是为了验证输入还是有其他主要原因?

最佳答案

  • 通常完全使用访问器/修改器是一种设计味道,表明您的类公共(public)接口(interface)不完整。通常来说,您需要一个有用的公共(public)接口(interface)来提供有意义的功能,而不是简单的获取/设置(这比我们在 C 语言中使用结构和函数要好一两个步骤)。每次你想写一个修改器,很多时候你想先写一个访问器,只需退后一步问问自己“我*真的*需要这个吗?”
  • 只是习惯用法的人可能不准备期待这样的功能,因此它会增加维护人员理解您的代码的时间。
  • 同名方法几乎与公共(public)成员相同:在这种情况下只需使用公共(public)成员。当方法做两件不同的事情时,给它们命名为两件不同的事情。
  • 通过非 const 引用返回的“mutator”将允许出现各种各样的别名问题,在这种情况下,有人会隐藏成员的别名,并依赖它在以后存在。通过使用单独的 setter 函数,您可以防止人们对您的私有(private)数据使用别名。

关于c++ - 简单的 C++ getter/setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18107784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com