【发布时间】: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 *'
【问题讨论】:
-
仅供参考:SO: Returning char * instead of string(昨天的问题非常相似。)
标签: c++ class c++11 inheritance exception