首页 > 解决方案 > 为什么我的 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

标签: c++referenceconstants

解决方案


该函数operator*()应该返回一个 const 引用const Ref,但为什么它只返回一个Ref

请注意, for const Ref,直接const限定在Ref(即引用)上,而不是被引用的类型。没有像 const 限定引用这样的东西,在这种情况下,const限定符被忽略了。这意味着与(即)const Ref相同。Refint&

[dcl.ref]/1

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 的左值引用”。—结束示例]


推荐阅读