4

可能的重复:
typedef 和 const 指针的容器

为什么代码会发出错误?

int main()
{
  //test code
  typedef int& Ref_to_int;
  const Ref_to_int ref = 10; 
}

错误是:

错误:从“int”类型的临时变量中“int&”类型的非常量引用的初始化无效</p>

我阅读了关于延长临时人员生命周期的帖子,其中说临时人员可以绑定到对 const 的引用。那为什么我的代码没有被编译?

4

3 回答 3

5

这里的类型ref实际上是reference to int而不是const reference to int。const 限定符被忽略。

8.3.2 美元 说

cv 限定引用格式错误,除非通过使用 typedef (7.1.3) 或模板类型参数 (14.3) 引入 cv 限定符,在这种情况下忽略 cv 限定符。

const Ref_to_int ref;等价于int& const ref;而不是const int& ref

于 2011-05-20T11:32:08.570 回答
1

与 typedef混合const并不像您想的那样工作。有关更多信息,请参阅此问题。这两行是等价的:

const Ref_to_int ref;
int& const ref;

您正在寻找:

const int& ref;

修复它的一种方法是将它包含在 typedef 本身中(尽管您可能应该重命名它):

typedef const int& Ref_to_int;
于 2011-05-20T11:33:44.047 回答
0

您不能向typedef. 它不像宏那样工作。

您的代码有效

int& const ref = 10;  // error

这是无效的。

于 2011-05-20T11:32:49.867 回答