无效初始化'int&'类型的非const引用来自临时的'int *'类型

时间:2013-09-15 01:22:55

标签: c++

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

我在();

的函数中得到了这个错误

'int&'类型的非const引用的无效初始化来自临时的'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; 
}

1 个答案:

答案 0 :(得分:2)

表达式begin()+index是指针类型;你需要添加一个解引用来使它成为一个参考:

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

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