我正在努力学习C++(目前正与C合作),我正在花时间寻找互联网以获得良好的教程(也许有人对我有好的建议).
但我找不到有关错误处理标准方法的信息.
所以假设我有一个像这样的简单类(我的example.h文件):
const int MAX = 1000;
class Example {
public:
Example(int x);
private:
int x_val;
}
Run Code Online (Sandbox Code Playgroud)
所以我只想检查,当创建类的对象时,如果允许给定的坐标,如果它高于允许的,则中止程序?
所以在.cpp文件中:
Example::Example(int x){
/*So is it common, to do something like this:*/
if (x >= MAX){
std::cerr << "Error while generating example object" << std::endl;
return 0;
}
/*or is this more convenient:*/
throw std::invalid_argument( "received to high value" );
x_val = x;
}
Run Code Online (Sandbox Code Playgroud)
当构造函数失败时抛出异常.
因为:
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |