首页 > 解决方案 > 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

标签: c++arraysclasspointerstemplates

解决方案


推荐阅读