c++ - 为什么我的 c++ 函数拒绝返回 const 引用?
问题描述
让我们看看下面的代码:
template<class T,class Ref>
class test{
private:
T data;
public:
test(const T& x):data(x){};
const Ref operator*(){
return data;
};
}
int main(){
test<int,int&> t(1);
*t=2;
return 0;
}
上面的代码运行良好。该函数operator*()
应该返回一个 const 引用const Ref
,但为什么它只返回一个Ref
?
解决方案
该函数
operator*()
应该返回一个 const 引用const Ref
,但为什么它只返回一个Ref
?
请注意, for const Ref
,直接const
限定在Ref
(即引用)上,而不是被引用的类型。没有像 const 限定引用这样的东西,在这种情况下,const
限定符被忽略了。这意味着与(即)const Ref
相同。Ref
int&
cv 限定的引用格式错误,除非通过使用 typedef-name ([dcl.typedef], [temp.param]) 或 decltype-specifier ([dcl.type.simple]) 引入 cv 限定符, 在这种情况下 cv 限定符被忽略。[ 例子:
typedef int& A; const A aref = 3; // ill-formed; lvalue reference to non-const initialized with rvalue
aref 的类型是“对 int 的左值引用”,而不是“对 const int 的左值引用”。—结束示例]
推荐阅读
- angular - ErrorHandler:与promise一起使用时无法获取错误对象
- java - 尝试每 5 个令牌
- ms-access - 如何在 MS Access 中修复我的宏的错误处理程序
- php - 重写规则部分重写 url
- arrays - MongoDB - 查找具有数组组合的任何文档
- html - 注销wordpress
- java - 如何在特定时间缓存数据 Spring Boot Rest Template
- ruby-on-rails - Doorkeeper - 如何在成功的第三方身份验证后生成正确的自定义响应?
- sql - SQL Server:如果列不为空,则显示为新行
- html - Firefox 书签面板改变了响应式 CSS 网格设计