0
我讀what-is-the-purpose-of-stdexceptionwhat和引用的std::exception
here從性病::例外比爲const char *
定義我需要從std::exception::what()
返回int
,因爲它是virtual
但我可以返回不同類型::什麼()等不會被返回類型覆蓋。我滾我自己的異常類
class BadLengthException : public std::exception
{
private:
int length;
const char* to_return;
public:
BadLengthException() = default;
BadLengthException(int new_length) : length(new_length) { to_return = new const char(length); }
~BadLengthException() = default;
const char* what() const throw() { return to_return; }
};
我將如何能夠改變返回類型純int
適合我的需求,使得
try
{
}
catch(BadLengthException bad_length)
{
std::cout << bad_length.what() <------- Got your int value
}
編輯我更改了代碼。測試顯示它提供了正確的值。我可以改進我所做的事嗎?考慮到我必須總是返回const char*
?
class BadLengthException : public std::exception
{
private:
const size_t size = 2;
char ref_arr[5] = { '1','2','3','4','5' };
int length;
char* to_return;
public:
BadLengthException() = default;
BadLengthException(int new_length) : length(new_length)
{
to_return = (char*)malloc(size * sizeof(char));
to_return[0] = ref_arr[length - 1];
to_return[1] = '\0';
}
~BadLengthException() = default;
const char* what() const throw() override { return to_return; }
};
你不知道。爲什麼不只是添加一個額外的方法?然後,你的異常的捕手可以說'bad_length.length()'或者其他。 – GManNickG
@GManNickG在這個特殊的問題,我正在解決,預期的輸出只限於'std :: exception :: what()' – Mushy
_I需要使用什麼,因爲我需要使用what_ ok – 2017-10-19 18:27:51