【发布时间】: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;
}
【问题讨论】:
-
numbers[MAX_ITEMS];不会创建数组或调整数组大小。 -
numbers[MAX_ITEMS];不会像您认为的那样做。充其量,什么都没有。在最坏的情况下,分段错误。你听说过std::vector或std::array吗? -
while (!inFile.eof()) {避免这种模式,因为:https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons -
你想要
std::array<int,MAX_ITEMS>in c++ -
还有
while (!inFile.eof())是wrong。
标签: c++ arrays class header-files