我是C++的初学者,因此对这个愚蠢的问题表示歉意。我在这里发布它,因为我无法在stackoverflow上找到类似的答案。在自定义异常的方法/构造函数签名中带和不带throw()的C++
我是通过在C++和我正在做一些手与自定义异常例外进步,我有这样的代码
class MyException: public std::exception{
public:
virtual const char* what() const throw() {
return "something bad happened";
}
};
// class that throws above exception
class canGoWrong {
public:
canGoWrong(){
throw MyException();
}
};
上面的代码被老师表示。构造函数刚刚实现了在基类exception中定义的虚函数。我到了那里。
现在,当我尝试使用不同的版本进行练习时,我尝试使用自定义函数而不是重新定义虚拟(因为C++没有严格执行接口的概念,如果我在这里错了,请纠正我的错误。)
我写它作为
class my_custom_shit_exception: public std::exception {
public:
const char* show() { // I omitted the const throw() here
return "This is an error encountered\n";
}
};
class myclass {
public:
myclass() {
throw my_custom_shit_exception();
}
};
总之,我没有发现这两种方式在活动的差异
public:
const char* show() {
return "This is an error encountered\n";
}
virtual const char* what() const throw() {
return "something bad happened";
}
那么为什么在what()虚函数中使用const throw()?它有什么不同?
谢谢大家。
+3
“因为C++没有严格执行接口的概念”它的确适用于纯虚函数,如果这就是你的意思。 –
+1
你省略的throw()是一个'异常说明'它告诉编译器该函数不会抛出任何异常,'what()'函数即不说它强制执行。为了清楚起见,请阅读异常规范。 –
+1
非常有趣的问题。这不是同一个问题,但我认为[这个是有帮助的](https://stackoverflow.com/questions/5230463/what-does-this-function-declaration-mean-in-c) –