从类型为"int*"的临时引用初始化类型为"int&"的非常量引用无效
invalid initialization of non-const reference of type 'int&' from a temporary of type 'int*'
我正在尝试在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()
函数获得的引用无效。
相关文章:
- 如何将 int 引用安全地转换为长引用?
- 运行时错误:引用绑定到类型为"int"的空指针
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 为什么这个函数可以返回C++int引用
- 创建<int>对整数数组指针的矢量引用 (C++)
- 对'cv::VideoCapture::VideoCapture(int)的未定义引用
- 函数 LNK2019 "int __cdecl __scrt_common_main_seh(void)" 中引用的未解析外部符号主错误 (?__scrt_common_main_seh@@YAHXZ
- for 循环说 - 错误 成员引用基类型"int [13]"不是结构或联合
- 引用数据的 int 指针
- 引用函数如何"int &foo();"工作?
- 编译Qt项目给出了对运算符delete(void*,unsigned int)的未定义引用
- 从emxArray_uint8_T检测到错误:.text+0xc1):未定义对"emxInit_uint8_T1(emxArray_uint8_T**, int)"的引用?
- 对 'i2c_smbus_read_word_data(int, 无符号字符)的未定义引用
- 错误:成员引用基类型"uint32_t"(也称为"无符号 INT")不是结构或联合
- 对ISPRIME(INT)的未定义引用,但已定义
- 在scanf中引用int
- 本地引用int是否有任何好处
- C++如何处理 const double&引用 int?
- 临时 B() 是否通过初始化下面的引用 int&ri 来延长其生命周期?
- 将枚举传递给引用int的函数