gpt4 book ai didi

c++ - 为什么我的输出中会出现随机数?

转载 作者:太空宇宙 更新时间:2023-11-04 15:33:54 24 4
gpt4 key购买 nike

请原谅我的代码,因为我对编程和 C++ 还很陌生。我正在创建一个 safearray 类来检查索引是否越界。我不明白为什么我在输出中得到一个随机数。我似乎只有在索引越界时才能得到数字。

安全阵列.h

#ifndef SafeArray_H
#define SafeArray_H

class SafeArray {
int upperbound;
int lowerbound;
int array[200];
public:
SafeArray(int, int);
int &operator[](int);
void print();
};

#endif

安全数组.cpp

#include "SafeArray.h"
#include <iostream>
using namespace std;


SafeArray::SafeArray(int l, int u) {
lowerbound = l;
upperbound = u;
for (int i = l; i < u; i++) {
array[i] = 0;
}
}

int &SafeArray::operator[](int index)
{

if (index > upperbound || index < lowerbound)
{
cout << "array out of bounds" << endl;
}
else {
return array[index];
}

}

void SafeArray::print() {
for (int i = lowerbound; i < upperbound; i++) {
cout << array[i] << endl;
}
}

测试器.cpp

#include "SafeArray.h"
#include <iostream>
using namespace std;

int main() {
int lowerbound;
int upperbound;
cout << "Enter a lower bound: ";
cin >> lowerbound;
cout << "Enter an upper bound: ";
cin >> upperbound;
SafeArray test = SafeArray(lowerbound, upperbound);
cout << test[101] << endl;
return 0;
}

输出:输入下限:0
输入上限:100
数组越界
255812108
按任意键继续。 .

.

最佳答案

垃圾值是因为函数必须返回一个值,除非它被声明为void。 .你遗漏了 return因此 Crom 只知道将返回什么用于打印,甚至程序是否能够继续打印。是Undefined Behaviour

我可以推荐一下吗

int &SafeArray::operator[](int index)
{

if (index > upperbound || index < lowerbound)
{
throw out_of_range("array out of bounds");
}
return array[index];
}

std::out_of_range 可以通过 #include <stdexcept> 找到

调用者必须捕获异常并继续或中止。例如:

try
{
cout << test[101] << endl;
}
catch(out_of_range & oor)
{
cout << oor.what() << endl;
}

现在您要么得到一个数字,要么得到一条错误消息,但绝不会同时得到。

关于c++ - 为什么我的输出中会出现随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40520569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com