gpt4 book ai didi

c++ - 测试 "Try and Catch"

转载 作者:行者123 更新时间:2023-11-28 02:48:50 24 4
gpt4 key购买 nike

在这个程序中,我使用模板类,我有一个头文件,这是我的主文件。我无法显示 (".....") IndexOutOfBounds 并将其显示在屏幕上。

#include "XArray.h"
#include <iomanip>
#include <string>

using namespace std;


template<class T>
void afriend ( XArray<T> );


int main()
{
XArray<double> myAD(18);
myAD.randGen(15, 100);

cout << myAD.getType() << endl;
cout << setprecision(1) << fixed << "\n\n Unsorted: " << myAD;

myAD.sort();
cout << "\n Now Sorted: " << myAD;
cout << "\n\n";

**try
{
cout << "A[-5] = " << setw(6) << myAD[-5] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
e.print();
}
try
{
cout << "A[8] = " << setw(6) << myAD[8] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
e.print();
}**



cout << "\n\n" << setprecision(2) << fixed;
cout << "Size = " << setw(6) << myAD.getSize() << endl;
cout << "Mean = " << setw(6) << myAD.mean() << endl;
cout << "Median = " << setw(6) << myAD.median() << endl;
cout << "STD = " << setw(6) << myAD.std() << endl;
cout << "Min # = " << setw(6) << myAD.min() << endl;
cout << "Max # = " << setw(6) << myAD.max() << endl;



return 0;
}

Array.h 文件作为保管箱链接发布

Array.h

Array.h 中 operator[] 的代码是:

template <class T>
T XArray<T>::operator[] (int idx)
{
if( (idx = 0) && (idx < size) )
{
return Array[idx];
}

else
{
throw IndexOutOfBound();
return numeric_limits<T>::epsilon();
}
}

最佳答案

虽然这个问题有些晦涩难懂,但请尝试这些建议。

首先,可能会发生 XArray<>::IndexOutOfBounds没有合适的复制ctor。您可以尝试通过 const 引用来捕获解决方法:

try
{
...
}
catch(const XArray<double>::IndexOutOfBound& e)
{
e.print();
}

标准库容器中的索引运算符不检查边界,有一个名为 at() 的特殊 getter 可以进行检查.如果XArray类在设计时考虑到了标准库,它的行为可能类似。

但是,为了获得更充分的响应,您需要更具体地描述您遇到的问题。

关于c++ - 测试 "Try and Catch",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508544/

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