【问题标题】:C++ different class getters [duplicate]C ++不同的类吸气剂[重复]
【发布时间】:2015-04-13 15:20:26
【问题描述】:

我对 C++ OO 比较陌生:

这个getter怎么样:

class A {
  B b;
public:
  B const &getB() const {
    return b;
  }
};

和这个不一样?

class A {
  B b;
public:
  const B &getB() const {
    return b;
  }
};

还有这个?

class A {
  B b;
public:
  const B &getB() {
    return b;
  }
};

哪一个是正确的?

编辑 这个问题在这里有答案:在http://isocpp.org/wiki/faq/const-correctness#overview-const中寻找“consistent const”

【问题讨论】:

  • 1 和 2 的意思是一样的,而且都是正确的。 3 在技术上并非不正确,但是由于 getB() 没有修改 A 实例,因此将函数设置为 const 是有意义的,这允许在 const A 对象实例(或引用等)上调用它.)
  • 感谢您的 cmets,但我认为这个问题有答案

标签: c++ oop


【解决方案1】:

关键字const 适用于他面前的东西(在他的左边),或者,如果它之前没有任何东西,它适用于它之后的东西(在他的右边)。你的 3 个案例在使用上都是正确的。

您可以参考这篇优秀的文章来了解更多关于 const-correctness 的信息:http://www.cprogramming.com/tutorial/const_correctness.html

【讨论】:

  • 谢谢,但我没看到有答案
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 2014-02-24
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2018-10-13
  • 2019-11-26
  • 1970-01-01
相关资源
最近更新 更多