Zam*_*mmy 4 c++ reference constants temporary
可能的重复:
typedef 和 const 指针的容器
为什么代码会发出错误?
int main()
{
//test code
typedef int& Ref_to_int;
const Ref_to_int ref = 10;
}
Run Code Online (Sandbox Code Playgroud)
错误是:
错误:从“int”类型的临时对象初始化“int&”类型的非常量引用无效
这里的类型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。