【问题标题】:Passing const value by reference通过引用传递 const 值
【发布时间】:2015-08-20 15:14:49
【问题描述】:

假设我有这个程序:

const int width = 4;

void test(int&){}

int main() {
    test(width);
}

这将无法编译。我注意到带有名称(例如 width )的常量值(也是枚举常量)不能通过引用传递。为什么会这样?

【问题讨论】:

  • 另一个选项是void test(const int&){},它既是常量又是引用。

标签: c++ pointers reference constants


【解决方案1】:

想象一下:

void test (int& j) { j++; }

如果test 确实改变了所引用事物的值,显然我们不能使用 const 参数调用它。如果没有,为什么要通过非常量引用来获取参数?

【讨论】:

    【解决方案2】:

    通过引用传递允许我们更改实际对象。 如果对象定义为const,则不能更改。这正是 const 的意思——它是恒定的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 2012-07-07
      • 1970-01-01
      • 2015-03-24
      相关资源
      最近更新 更多