我的讲义说
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/