gpt4 book ai didi

C++自制异常处理失败

转载 作者:行者123 更新时间:2023-11-28 02:12:16 25 4
gpt4 key购买 nike

我正在上 C++ 类(class),其中一项任务如下:

他们给了我们一个主程序,我们必须编写它背后的代码。这是代码:

vector<int> iv(4);

iv[3]=42;

cout << iv[3] << endl; // prints "42"

try {
cout << iv[1] << endl; // throw exception
}
catch (vector<int>::Uninitialized&){
cout << "Uninitialized vector element!" << endl;
}

return 0;

我为 vector 模板想出了这段代码:

T* data;
unsigned int size;

public:
class Uninitialized{};
explicit vector(int size) {
data = new T[size];
this -> size = size;
for (unsigned i = 0; i < size; i++) {
data[i] = 0;
}
}

~vector() {
delete [] data;
}

T& operator[](int index) {
if (index >= size) {
abort();
}
return data[index];
}

friend ostream& operator<< (ostream& o, const T& t) {
if (t == 0)
throw Uninitialized();
else
return o << t;
}

但是,friend 方法从未被调用,因此从未抛出异常。

最佳答案

你在扔

iv[3]=42;

因为此时,data[3] == 0

请记住,即使在您的作业中,您也在调用 operator[];它不关心(甚至不知道)您是否需要 T& 进行读取或写入。

您应该首先使用调试器逐步解决此类问题(通常,代码足够简单并且您知道如何使错误出现的问题)。您会发现这一点——您会立即看到异常并没有在您认为的地方被抛出。

关于C++自制异常处理失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35255379/

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