c++ - 为什么 const 变量不能通过引用传递?

标签 c++ constants pass-by-reference

我的讲义说

The argument to a reference parameter must be a variable, not a constant or an expression.

因此

int f(double & var); // function prototype
...
const double t = 4.0;
int ret = f(t); 

f(t) 非法。

但我不明白,为什么t是非法的。 t 是一个常量,但仍然是一个变量,我认为通过引用传递 t 没有任何错误。

最佳答案

让我将我的评论增强为答案:

首先,t不是常量,而是 const 变量。常数为 4.0。你的讲义基本上是说你不能做像 int ret = f(4.0); 这样的事情

其次,您看到的是类型不匹配。 const作为限定符是类型的一部分。您不能执行以下操作:

const int x = 1;
int& ref_x = x;

error: binding reference of type ‘int&’ to ‘const int’ discards qualifiers

尽管如此,通过 const 是合法的。限定变量作为引用,要么使用 const 引用,要么放弃 const:

  • 使用 const 引用 const int& const_int_ref = x;
  • 使用const_cast:int& rx = const_cast<int&>(x);

只要有可能,我更喜欢第一个。

关于c++ - 为什么 const 变量不能通过引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53694899/

相关文章:

c++ - 在复制构造函数中调用 const 引用的方法

objective-c - Objective-c 中的 const 关键字

c++ - 在哪里可以找到 Qt 库的开源小部件?

java - 通过 JNI 的数据未正确传递

c - 关于 C const 的问题

go - 通过引用分配

c++ - 用于存储涉及引用的 "equation"的库?

c++ - 在 x64 中将结构作为参数传递时监 window 口中的异常值

c++ - 优化读写大数据(C++)

javascript - 如果JavaScript对象是通过引用传递的,为什么更新属性值不会更新局部变量