c++ - 我正在尝试使用类创建具有已指定的最大大小的数组,但似乎未创建该数组

标签 c++ arrays class header-files

我试图在我的UnsortedList类中创建一个数组。我指定在头文件中创建一个数组,并且还指定了等于10的MAX_SIZE。但是,每当我创建该类的对象时,默认构造函数都不会使用MAX_SIZE创建该数组。我不确定自己在做什么错。我还收到一条错误消息:“变量'myList'周围的堆栈已损坏”。另外,就像一个旁注,我可以在调用默认构造函数时初始化数组值,而不是创建一个函数来执行此操作吗?
“UnsortedList.h”头文件:

#pragma once

class UnsortedList {
public:
    UnsortedList();
    bool IsFull(); //Determines whether the list is full or not (returns T or F)
    int GetLength(); //Gets the length of the list
    void SetListValues();
private:
    int length;
    const int MAX_ITEMS = 10;
    int numbers[];
};
“UnsortedList.cpp”文件:
#pragma once
#include "UnsortedList.h"
#include <fstream>
#include <iostream>
using namespace std;

UnsortedList::UnsortedList() {
    length = 0; //sets length to 0
    numbers[MAX_ITEMS]; //sets array maximum size to MAX_ITEMS (10 as indicated in UnsortedList.h)
}

bool UnsortedList::IsFull() {
    return (length == MAX_ITEMS);
}

int UnsortedList::GetLength() {
    return length;
}

void UnsortedList::SetListValues() {
    ifstream inFile;
    inFile.open("values.txt");

    int x = 0;
    while (!inFile.eof()) {
        inFile >> numbers[x];
        x++;
    }
}
“main.cpp”文件:
#include <iostream>
#include <string>
#include "UnsortedList.h"
using namespace std;

int main() {

    UnsortedList myList;
    myList.SetListValues();

    return 0;
}

最佳答案

我建议您使用std::arraystd::vector,但是如果必须使用C数组,则 header 中的定义需要更正:

class UnsortedList {
// ...
    const static int MAX_ITEMS = 10;
    int numbers[MAX_ITEMS];
};
您可以在构造函数中删除相应的行。文件读取方法还需要更正:
void UnsortedList::SetListValues() {
    ifstream inFile;
    inFile.open("values.txt");

    int x = 0;
    int read_value;

    // x < MAX_ITEMS to avoid out of bounds access
    while (x != MAX_ITEMS && inFile >> read_value) 
    {
        numbers[x++] = read_value;

        length++; // I assume you also want to increment the length at this point?
    }
}


编辑:正如@πάνταῥεῖ指出的那样,当标准提供std::array时,没有充分的理由使用C样式数组。变化不大,它声明为:
std::array<int, MAX_ITEMS> numbers;
您可以将operator[]与C数组一起使用。这是可取的,因为它提供了更丰富的API,并且可以像其他C++容器(即STL算法)一样使用。

关于c++ - 我正在尝试使用类创建具有已指定的最大大小的数组,但似乎未创建该数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63801894/

相关文章:

c++ 创建新的 LinkedList 类 : Clear() method pointer being freed not allocated

c++ - 在 C++ 中的文件(日志文件)中添加新行

c - 传递 char 的二维数组作为参数

java - 使用 opencsv (java) 读取 .csv 文件时跳过空行

c# - List<T> 在类中使用

c++ - 等号对大括号初始化有影响吗?例如。 'T a = {}' 与 'T a{}'

c++ - 如何获取 com_ptr_t 中指针的地址

c++ - 错误 : invalid type argument of unary '*'

python - 类问题,__init__ 参数不匹配

PHP 从子上下文中以公共(public)方式调用 protected 方法