【问题标题】:I am trying to create an array with an already specificed maximum size using a class but the array does not seem to be created我正在尝试使用一个类创建一个具有已经指定的最大大小的数组,但该数组似乎没有被创建
【发布时间】:2020-09-08 21:37:41
【问题描述】:

我正在尝试在我的 UnsortedList 类中创建一个数组。我指定在头文件中创建一个数组,并且我还指定了 MAX_SIZE,它等于 10。但是,每当我创建类的对象时,默认构造函数不会创建具有 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;
}

【问题讨论】:

标签: c++ arrays class header-files


【解决方案1】:

我建议您使用std::arraystd::vector,但如果您必须使用C 数组,那么您在标题中的定义需要更正:

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;

您可以像使用 C 数组一样使用 operator[]。这是更可取的,因为它提供了更丰富的 API,并且可以像其他 C++ 容器一样使用,即与 STL 算法一起使用。

【讨论】:

  • 在标题定义中,我尝试执行int numbers[MAX_ITEMS];,但收到错误消息“非静态成员引用必须与特定对象相关
  • @AG77 我忘记了size成员前面的static关键字!
  • @Mansoor "但是如果你必须使用 C 数组" 没有理由。如果您需要与纯 c API 交互,则可以使用 std::array::data()。如果您提到这一点,那将是一个很大的改进。
  • @πάνταῥεῖ 人为地强加要求,比如学术练习?我同意你的观点。答案与std::array 相似。
  • @Mansoor “像学术练习那样人为地强加要求?” 好吧,在好的课程中,他们应该教授如何编写不易出错且可用于生产的代码。但是老师(尤其是年长的老师)很懒惰,懒得更新他们的课程材料。 - 只是我的 2 美分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
相关资源
最近更新 更多