为什么我的输出中会得到随机数
Why am I getting random numbers in my output?
请原谅我的代码,因为我对编程和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 只知道将返回打印的内容,或者即使程序是否可以存活到打印中。这是未定义的行为
我可以推荐吗
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;
}
现在,您要么收到数字,要么收到错误消息,但永远不会同时收到两者。
int &SafeArray::operator[](int index)
{
int *p;
p = array;
if (index > upperbound || index < lowerbound)
{
cout << "array out of bounds" << endl;
}
else {
return array[index];
}
}
如果index
超出界限,则[]
运算符不会返回任何内容。这是一种未定义的行为。另外,您的阵列用户可能想知道发生了意外情况。这是一种实现此目的的方法:
int &SafeArray::operator[](int index)
{
int *p;
p = array;
if (index > upperbound || index < lowerbound)
{
throw std::exception("array out of bounds");
}
else {
return array[index];
}
}
//...
try
{
SafeArray test = SafeArray(lowerbound, upperbound);
cout << test[101] << endl;
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 我的字符计数代码计算错误.为什么
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- cmake在我的项目中所需的所有静态库都不成功
- 为什么我的代码在输出中增加了93天
- 为什么 rand 不在我的代码中生成随机数?
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- 我正在努力在随机数组中查找最小值,有人知道为什么我的代码不起作用?C++
- 测量我的随机数数组打印的时间始终显示为 0 秒
- 我的随机数生成器不断获得相同的数字?(C )
- 我如何确保我的随机数在兰德生成的0和1之间不是0
- 我的随机数生成器正在打印重复的数字
- 我的C++代码不适用于较大的随机数组
- 为什么我的随机数程序输出垃圾
- 我的程序在运行时不会打印任何内容,输入几个随机数后它会工作(有很多错误)
- 为什么我的输出中会得到随机数
- 我能让我的while循环在每次循环时创建一个新的随机数吗
- 我的包编译后,get函数可以工作,除了它打印随机数的doubles
- 我的c++随机数不是随机的