gpt4 book ai didi

c++ - 在 C++ 中捕获错误的数组引用

转载 作者:搜寻专家 更新时间:2023-10-31 00:06:03 24 4
gpt4 key购买 nike

如何在 C++ 中捕获错误的数组引用?为什么以下代码不起作用:

    #include <exception>

int * problemNum = new int;
int (* p [100])() = {problem1, problem2, problem3};

...

try {
cout << (*p[*problemNum-1])();
}
catch (exception){
cout << "No such problem";
}

我的编译器说:Euler.exe 中 0xcccccccc 处未处理的异常:0xC0000005:访问冲突。 当我通过输入 0 作为 *problemNum 启动错误引用时。

最佳答案

alamar 是对的 - C++ 不会捕获这种类型数组的异常。

改为使用 STL vector :

#include <exception>
#include <vector>

int * problemNum = new int;
std::vector<int(*)()> p;
p.push_back(problem1);
p.push_back(problem2);
p.push_back(problem3);

...

try {
cout << p.at(*problemNum-1)();
}
catch (exception){
cout << "No such problem";
}

关于c++ - 在 C++ 中捕获错误的数组引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/900199/

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