我正試圖覆寫what函式,以便列印我自己的自定義錯誤資訊。
所有的資訊都有相同的開頭,因此我認為最好能做到以下幾點:
所有的資訊都有相同的開頭。
class Exception : public std::exception
{
public:
virtual const char* what() const throw() noexcept
{
return ("發生了一個與游戲有關的錯誤。" "class name")。)
//note: "class name" above is the error message I want to print .
//depending on the situation, which can vary a lot(we have 8 different messages).
}
};
///"類名 "的例子/也就是我們所說的錯誤資訊:。
class IllegalArgument : public Exception {};
class IllegalCell : public Exception {};
我的問題如下 :
我不太明白如何根據我收到的錯誤列印不同的訊息 這意味著我不得不在IllegalArgument、IllegalCell和其他每一個錯誤類中添加一個什么函式,這在我看來是很糟糕的,因為有太多的函式需要維護并不斷地更新。
uj5u.com熱心網友回復:
你可以把類的名字傳給Exception建構式,并存盤這個名字:
class Exception : public std::exception {
public:
virtual const char *what() const noexcept{
return m_.c_str()。
}
protected:
Exception(std::string const& name) : m_{"發生了一個與游戲相關的錯誤。" name} {}
private:
std::string m_;
};
class IllegalArgument。public Exception {
public:
IllegalArgument() : Exception("IllegalArgument") {};IllegalArgument()
};
如果你不想每次都麻煩地撰寫默認的建構式,你可以撰寫一個宏來定義你的子例外。
如果你對生成的名字沒有意見,另一個選擇是使用typeid(),例如:
class Exception : public std::exception {
public:
virtual const char *what() const noexcept{
//你在這里需要一個靜態的東西來維護緩沖區,因為你要回傳一個的緩沖區。
// const char*, not a string, and you cannot construct this string in the
//建構式,因為typeid()在建構式中無法正常作業。
//
static const std::string s =
std::string("A game related error has occurred: ") typeid(*this) 。 name()。
return s.c_str()。
}
};
class IllegalArgument : public Exception { };
由typeid(*this).name()生成的名稱不是標準的,例如,用gcc我得到15IllegalArgument,所以這取決于你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/314164.html
標籤:
