I'm trying to recreate the vector class in C++
I obtain this error int the function at();
invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'
Isn't it possible to return a pointer as address even if the function is supposed to return a reference?
the code looks like:
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; }
Vector<int> vec1(4);inmain.&or missing*somewhere ..at()returns a reference.begin() + indexis pointer arithmetic, evaluating to an address. You need to return*(begin() + index), and I highly advise you range-check that first, and throw an exception if its out of bounds. And note, unless you want to support negative offsets, and I can't imagine you do, your index parameter should be unsigned.