c++ - nullptr 未在此范围类模板中声明 - C++
问题描述
我正在尝试创建一个名为 Vector 的类模板,用于创建任何类型的动态数组。当调用我的默认构造函数时,它会创建一个新数组,并调用一个方法 initialize,该方法使用 nullptr 将动态数组的所有值初始化为 null。出于某种原因,在编译时出现错误:'nullptr' was not declared in this scope
在那一行。可能是什么问题?
此外,对我的课程的任何反馈都会很好。由于此错误,我尚未对其进行测试,但我希望它能够成功处理任何类型的数组,尤其是对象数组。
矢量.h:
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
class Vector
{
public:
Vector(int size = 10);
~Vector();
void initialize(int from);
void expand();
void push(const T &element);
int size(){return this->nrofel;}
T& operator[](const int index);
private:
T **data;
int capacity;
int nrofel;
};
template <class T>
Vector<T>::Vector(int size){
this->capacity = size;
this->nrofel = 0;
this->data = new T*[this->capacity];
initialize(this->nrofel);
}
template <class T>
T& Vector<T>::operator[](const int index){
if(index < 0 || index >= this->nrofel){
throw("Out of bounds.");
}
return *this->data[index];
}
template <class T>
void Vector<T>::initialize(int from){
for(size_t i = from; i < capacity; i++){
this->data[i] = nullptr;
}
}
template <class T>
Vector<T>::~Vector(){
for(size_t i = 0; i < capacity; i++){
delete this->data[i];
}
delete[]this->data;
}
template <class T>
void Vector<T>::expand(){
this->capacity *= 2;
T ** tempData = new T*[this->capacity];
for(size_t i = 0; i < this->nrofel; i++){
tempData[i] = this->data[i];
}
this->data = tempData;
initialize(this->nrofel);
}
template <class T>
void Vector<T>::push(const T& element){
if(this->nrofel >= this->capacity){
this->expand();
}
this->data[this->nrofel++] = new T(element);
}
#endif // VECTOR_H
解决方案
推荐阅读
- r - 如何抑制来自 stats:::regularize.values 的警告?
- docker - Docker构建后的虚拟缩小
- sql - 如何使用“group by”选择“插入”并在Oracle中具有唯一的约束键?
- java - 从 RecycleView 适配器写入 SQLite DB
- c# - 加载 formComponent 时,Form.Shown 函数中的图形正在重置
- python - 寻找一种使用 python 将 xlsx 表导入谷歌表的方法 - 而不是我必须在每台机器上设置的 API
- ruby-on-rails - Slack 没有为斜杠命令正确格式化我的 JSON
- c - 将 pdm 数据转换为 pcm 或其他音频数据格式
- binary - 如何将反汇编指令转换为 gdb 中的二进制显示?
- mongoose-schema - 在 Mongoose 模式中验证 ISO 国家代码