【发布时间】:2023-03-18 20:12:01
【问题描述】:
在我的程序中,调用时出现分段错误
cout << ( ball(1,0,0) ).getName();
当我打电话时用于测试目的( ball(1,0,0) ).getName();
我按预期得到一个异常并且程序没有崩溃。
这里可能有什么问题?我尝试重载 ostream,但似乎没有用。程序的相关部分是:
球和场::operator()(int x, int y, int z){
try{
if (arr[x][y][z]==1){ // When it's 1, there is a ball in that coord
return search(root,x,y,z); // Return ball instance
}else{
throw ballException(); // 'Error: Ball not found'
}
}catch(std::exception &e){
std::cout << e.what() << std::endl;
}
}
const string& Ball::getName() const {
try{
return this->name;
}catch(std::exception & e){
}
}
Ball::Ball(const string& name, const string& type, int size){
this->name =name;
this->type = type;
this->size= size;
}
球例外是:
class ballException: public exception {
virtual const char* what() const throw() {
return "Error: No Ball in the coordinates!";
}
};
【问题讨论】:
-
好的,我已经包含了相关部分的代码
-
你知道分段错误不是例外吗?
-
是的,它应该打印出异常,但我在调用 std::cout 时出现分段错误
-
如何声明名称、类型和大小?还有 BallException?
标签: c++ exception segmentation-fault cout ostream