C++ 无效数组<T、N> 下标

C++ invalid array<T, N> subscript

本文关键字:gt 下标 无效 lt C++ 数组      更新时间:2023-10-16

我在C++中制作了一个基本的类/结构集合,其中包含我没有包含的类Book,以及其他一些类,以及struct FixedSizeBookCollection。但是,使用 FSCB 时,它无法按计划工作:

书籍.h

template<size_t Size> struct FixedSizeBookCollection : private std::array<const Book*, Size>{
    FixedSizeBookCollection(const char* Name) : name_(Name){}
    void operator+=(const Book& Book)try{
        if((*this).size() > Size){
            std::ostringstream errorMessage;
            errorMessage << "The FixedSizeBookCollection " << name_ << "'s size capacity has been overfilled" << std::endl;
            throw std::exception(errorMessage.str().c_str());
        }
        /* Line 97 - */ (*this).at(currentPos++) = &Book;
    }catch(const std::exception& e){
        std::ostringstream errorMessage;
        errorMessage << e.what() << " - on line (approx.) " << (__LINE__ -3);
        throw std::exception(errorMessage.str().c_str());
    }
private:
    const char* name_;
    int currentPos;
};

而且主要是.cpp

FixedSizeBookCollection<5> Collection("My Fixed Size Collection");
Collection += MyBook;

但是我得到错误:

Error: invalid array <T, N> subscript on line (approx.) 97

问题出在哪里?

您的currentPos未初始化。它可以具有任何值。将此变量初始化添加到 c-tor 中 0。