在C ++ 11中继承异常? [英] Inheriting Exceptions in C++11?
问题描述
我有一个名为 Matrix< t>
的类,我的教授要求我编写一个异常类:
I have a class called Matrix<t>
, My professor asked me to write an exception class:
Matrix::IllegalInitialization
它包含功能 what()
,所以我写了(在Matrix.h中):
Such that it includes the function what()
, So I wrote (In Matrix.h):
template<class T>
class Matrix<T>::IllegalInitialization {
public:
std::string what() const {
return "Mtm matrix error: Illegal initialization values";
}
};
但是我有一个问题,该类不能继承Exception,如何解决此问题?
But I have a problem that this class doesn't inherit Exceptions, how to fix this?
我要执行以下操作:
try {
Dimensions dim(0,5);
Matrix<int> mat(dim);
} catch (const mtm::Matrix<int>::IllegalInitialization & e){ cout<< e.what() <<endl;
}
修改:这是我的代码的样子吗?
Is this how should my code look like?
template<class T>
class Matrix<T>::IllegalInitialization : public std::exception {
public:
const char* what() const override {
return "Mtm matrix error: Illegal initialization values";
}
};
我得到了:
错误:覆盖函数的异常说明比基本版本更宽松
error: exception specification of overriding function is more lax than base version
推荐答案
std :: exception
的 what()
方法为(cf
The what()
method of std::exception
is (cf cppreference):
virtual const char* what() const noexcept;
您的方法未声明为 noexcept
,因此无法覆盖 std :: exception :: what()
.
Your method is not declared noexcept
hence it cannot override std::exception::what()
.
这篇关于在C ++ 11中继承异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!