我写了一个代码,而不是抛出派生类异常,而是从派生类中抛出基类异常
#include <iostream>
using namespace std;
class Base {
public:
class BaseException {};
class DerivedException : public BaseException {};
virtual void f() throw(DerivedException) {
throw DerivedException();
}
virtual void g() throw(BaseException) {
throw BaseException();
}
};
class Derived : public Base {
public:
void f() throw (BaseException)
{
throw BaseException();
}
virtual void g() throw (BaseException)
{
throw DerivedException();
}
};
int main()
{
Derived D;
return 0;
}
它无法编译并说
Line 18: error: looser throw specifier for 'virtual void Derived::f() throw (Base::BaseException)'
compilation terminated due to -Wfatal-errors.
我在网上搜索,似乎派生类违反了在基类中订立的合同。
我怀疑基类为派生类对象订立了合同,但是,我正在使用基类,所以合同在哪里被破坏。