从类型为"int*"的临时引用初始化类型为"int&"的非常量引用无效

invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'

本文关键字:引用 int 类型 无效 非常 常量 初始化      更新时间:2023-10-16

我正在尝试在C++中重新创建向量类

我在函数 at() 中获得了此错误;

从类型为"

int*"的临时引用初始化类型为"int&"的非常量引用无效

即使函数应该返回引用,是否也无法返回指针作为地址?

代码如下所示:

template<typename T>
class Vector
{
public:
   explicit Vector(int initSize = 0);
   Vector(const Vector & rhs) throw (std::bad_alloc);
   ~Vector();
   const Vector & operator=(const Vector & rhs) throw (std::bad_alloc);
   void resize(int newSize);
   void reserve(unsigned int newCapacity);
   bool empty() const;
   int size() const;
   int capacity() const;
   T & operator[](int index);
   const T & operator[](int index) const;
   T & at(int index) throw (std::out_of_range);
   void push_back(const T & x) throw (std::bad_alloc);
   T pop_back();
   const T & back() const;
   typedef T * iterator;
   typedef const T * const_iterator;
   iterator insert(iterator it, const T& x) throw (std::bad_alloc);
   iterator begin();
   const_iterator begin() const;
   iterator end();
   const_iterator end() const;
private:
   int theSize;
   unsigned int theCapacity; 
   T * objects; 
};
#include "vector.hpp"
#endif /* VECTOR_HPP_ */
template<typename T>
Vector<T>::Vector(int initSize):theSize
(initSize),theCapacity(128),objects(0)
{
}
typename Vector<T>::iterator Vector<T>::begin()
{
    return objects;
}
template<typename T>
T & Vector<T>::at(int index) throw (std::out_of_range)
{
    //if (index<=theSize)
        return (begin()+index);
}
int main() 
{
        Vector<int>* vec1=new Vector<int>(4);
    cout<<vec1->at(2)<<endl;
        return 0; 
}

表达式 begin()+index 是指针类型;您需要添加取消引用以使其成为引用:

template<typename T>
T & Vector<T>::at(int index) throw (std::out_of_range)
{
    return *(begin()+index);
}

请注意,这可能不安全,因为重新分配objects的操作会使通过at()函数获得的引用无效。