在我的 main() 中,我正在创建在构造函数中进行错误检查的对象。 如果发生错误,我想从 main() 返回错误代码以退出程序。
我应该在 main() 中使用回调来返回错误代码,还是不应该在构造函数中进行错误检查;将其移动到可以向 main() 返回错误代码的成员函数?
最佳答案
你可以为此使用throw
:
struct C
{
C() {throw std::runtime_error("for the example");}
};
int main()
{
try
{
C c;
// Do normal stuff (that never happen due to throw)
return 0;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return -1;
}
}
关于c++ - 从对象内部返回值给 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038787/