1

我正在尝试在 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; 
}
4

1 回答 1

2

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

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

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

于 2013-09-15T01:28:59.693 回答