为什么我的c ++函数拒绝返回const引用?

问题描述 投票:1回答:2

我们来看下面的代码:

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 referenceconst Ref,但为什么它只返回一个Ref

c++ reference const
2个回答
1
投票

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

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

[dcl.ref]/1

除非通过使用typedef-name([dcl.typedef],[temp.param])或decltype-specifier([dcl.type.simple])引入cv-qualifiers,否则Cv限定的引用是不正确的。 ,在这种情况下,cv限定符被忽略。 [实施例:

typedef int& A;
const A aref = 3;   // ill-formed; lvalue reference to non-const initialized with rvalue

aref的类型是“对int的lvalue引用”,而不是“对const int的lvalue引用”。 - 结束例子]


-2
投票

编辑:好的,如果你想在编译时出现编译时错误,你可以像这样写:

template<class T> 
class test { 
private: 
   T data; 
public: 
   test(const T& x):data(x){};
   const T& operator*() { return data; }
};
int main(){ 
    test<int> t(1); 
    *t=2;    // error
    return 0; 
}
© www.soinside.com 2019 - 2024. All rights reserved.