C2440 無法將 int 轉換為 int &

C2440 Can't transform int to int &

本文关键字:int C2440      更新时间:2023-10-16

我的代码遇到了一些麻烦。我想我错过了一些指针,但找不到它。

这是我的类代码:

template <class T, class U>
class KeyValue
{
private:
    T _key;
    U _value;
public:

    KeyValue();
    KeyValue(T key, U value)
    {
        this->_key = key;
        this->_value = value
    };
    T GetKey() { return this->_key; }
    U GetValue() { return this->_value; }
};

错误发生在:

template<class T, class U>
inline U & SparseArray<T, U>::operator[](T key)
{
    for (std::list<KeyValue<T, U>>::iterator it = list->begin(); it != list->end(); it++)
    {
        if (it->GetKey() == key)
        {
            return it->GetValue();
        }
    }
    return (list->insert(list->begin(), KeyValue<T, U>(key, U())))->GetValue();
}

GetValue()按值返回,这意味着它为您提供了一个 prvaluePRvalue 是一个临时对象,在完整表达式的末尾超出范围。 因此,您不允许将左值引用绑定到它,而返回类型(U &(就是这样。

如果要返回对基础_key的引用,则GetValue()需要返回一个左值引用,例如

T& GetKey() { return this->_key; }