【问题标题】:Avoiding repetition of const and non-const version of getters?避免重复 const 和非常量版本的 getter?
【发布时间】:2013-07-06 20:31:30
【问题描述】:
struct BananaHolder
{
    vector<Banana>& getBananas();
    const vector<Banana>& getBananas() const;
};

我的课堂上充斥着这种重复。

有没有更干净、更优雅的替代方案?

【问题讨论】:

  • 也许一直返回引用并不是最好的选择。
  • 在我的情况下它是必需的。
  • @AndyProwl 好吧。您能否将其复制粘贴到答案中以便我接受?
  • @VittorioRomeo: 这样做了:) 删除我之前的评论...

标签: c++ c++11 constants getter const-correctness


【解决方案1】:

如果您的类必须返回引用,并且如果在可修改对象上调用时它必须返回对可修改向量的引用,那么我认为没有办法避免重复- 至少,不是重复声明。

请注意,某些类型的标准库也会遇到同样的问题。例如,诸如std::vector 之类的序列容器同时具有const 和非const 重载operator []at()back()front()data() 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-28
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多