简体   繁体   English

继承 C++11 中的异常?

[英]Inheriting Exceptions in C++11?

I have a class called Matrix<t> , My professor asked me to write an exception class:我有一个名为Matrix<t>的 class ,我的教授让我写一个异常 class:

Matrix::IllegalInitialization

Such that it includes the function what() , So I wrote (In Matrix.h):这样它包括 function what() ,所以我写了(在 Matrix.h 中):

template<class T>
class Matrix<T>::IllegalInitialization {
public:
    std::string what() const {
        return "Mtm matrix error: Illegal initialization values";
    }
};

But I have a problem that this class doesn't inherit Exceptions, how to fix this?但是我有一个问题,这个 class 不继承异常,如何解决这个问题?

I want the following to work:我希望以下工作:

     try {
         Dimensions dim(0,5);
         Matrix<int> mat(dim);
} catch (const mtm::Matrix<int>::IllegalInitialization & e){ cout<< e.what() <<endl;
}

Edit: 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";
   }
};

I am getting:我正进入(状态:

error: exception specification of overriding function is more lax than base version错误:覆盖 function 的异常规范比基本版本更宽松

The what() method of std::exception is (cf cppreference ): std::exceptionwhat()方法是(cf cppreference ):

virtual const char* what() const noexcept;

Your method is not declared noexcept hence it cannot override std::exception::what() .您的方法未声明为noexcept因此它不能覆盖std::exception::what()

This is an example with a little bigger amount of code lines, but it more flexible这是一个代码行多一点的例子,但它更灵活

Usage example:使用示例:

try {
    throw MatrixErrors{ErrorCode::kIllegalInitialization};
} catch (const MatrixErrors& error) {
    std::cerr << error.what() << std::endl;
    return 1;
}

The code:编码:

enum class ErrorCode {
  kIllegalInitialization,
};

// Helper function to get an explanatory string for error
inline std::string GetErrorString(ErrorCode error_code) {
  switch (error_code) {
    case ErrorCode::kIllegalInitialization:
      return "Mtm matrix error: Illegal initialization values";
  }
  return {};
}

class MatrixErrors : public std::runtime_error {
 public:
  explicit MatrixErrors(ErrorCode error_code) : std::runtime_error{GetErrorString(error_code)}, code_{error_code} {}

  ErrorCode GetCode() const noexcept { return code_; }

 private:
  ErrorCode code_;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM