为什么我的输出中会得到随机数

Why am I getting random numbers in my output?

本文关键字:随机数 我的 输出 为什么      更新时间:2023-10-16

请原谅我的代码,因为我对编程和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;
}