为什么我的输出中会出现随机数? 请原谅我的代码,因为我对编程和C++比较陌生。我正在创建一个safearray类,用于检查索引是否超出范围。我不明白为什么我的输出中会有一个随机数。我似乎只有在索引超出范围时才能得到数字
SafeArray.h为什么我的输出中会出现随机数? 请原谅我的代码,因为我对编程和C++比较陌生。我正在创建一个safearray类,用于检查索引是否超出范围。我不明白为什么我的输出中会有一个随机数。我似乎只有在索引超出范围时才能得到数字,c++,arrays,C++,Arrays,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 SafeArray.cpp #include "Sa
#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
SafeArray.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;
}
}
#包括“SafeArray.h”
#包括
使用名称空间std;
SafeArray::SafeArray(int l,int u){
lowerbound=l;
上限=u;
对于(int i=l;i上界| |索引<下界)
{
cout垃圾值是因为函数必须返回一个值,除非它被声明为void
。您遗漏了返回值
,因此Crom只知道将返回什么进行打印,甚至程序是否能够继续打印。它是
我可以推荐你吗
int &SafeArray::operator[](int index)
{
if (index > upperbound || index < lowerbound)
{
throw out_of_range("array out of bounds");
}
return array[index];
}
现在,您要么得到一个数字,要么得到一条错误消息,但决不能同时得到两者。垃圾值是因为函数必须返回一个值,除非它被声明为void
。您遗漏了返回值
,因此Crom只知道将返回什么进行打印,甚至程序是否能够继续打印。这是错误的
我可以推荐你吗
int &SafeArray::operator[](int index)
{
if (index > upperbound || index < lowerbound)
{
throw out_of_range("array out of bounds");
}
return array[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;
}
int &SafeArray::operator[](int index)
{
if (index > upperbound || index < lowerbound)
{
throw out_of_range("array out of bounds");
}
return array[index];
}
try
{
cout << test[101] << endl;
}
catch(out_of_range & oor)
{
cout << oor.what() << endl;
}