【问题标题】:Exceptions Using Inheritance?使用继承的异常?
【发布时间】:2020-10-16 22:34:22
【问题描述】:

我写了以下代码:

class GameException : public mtm::Exception {
};

class IllegalArgument : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalArgument";
    }
};

class IllegalCell : public GameException {
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: IllegalCell";
    }
};

如何在此处使用继承来防止某些代码重复?如您所见,我返回的是相同的句子,但结尾不同(这是类名)。 我虽然关于实现 GameException 如下:

class GameException : public mtm::Exception {
     std::string className;
public:
    const char *what() const noexcept override {
        return "A game related error has occurred: "+className;
    }
};

但是我怎样才能为我的其他类更改 className 的值? 另外,我收到了错误:

类型的返回值没有可行的转换 'std::__1::basic_string' 到函数返回类型 'const char *'

【问题讨论】:

标签: c++ class c++11 inheritance exception


【解决方案1】:

错误是因为char [] + std::string 产生了一个std::string,但该方法被声明为返回一个const char *

为了避免返回临时指针时出现问题,我建议这样做:

class GameException : public mtm::Exception {
     std::string message;
public:
    GameException(const std::string& pref) 
      : message("A game related error has occurred: " + pref)
    {}
    const char* what() const noexcept override {
        return message.c_str();
    }
};

然后只需要派生类

struct some_excpetion : GameException {
     some_exception() : GameException("some_exception") {}
};

PS:从std::runtime_error 继承会更方便,因为它已经实现了what(),并带有一个构造函数,该构造函数接受what() 返回的消息。您基本上可以删除您的GameException 并从std::runtime_error 继承。

【讨论】:

  • @Josh fyi(不确定是不是你的,但是......)“谢谢”功能没有任何作用。说“谢谢”的最佳方式仍然是投票
  • 投了你的票,抱歉耽搁了
猜你喜欢
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 2012-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多