2017-10-19 329 views
0

我讀what-is-the-purpose-of-stdexceptionwhat和引用的std::exceptionhere從性病::例外比爲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; } 

}; 
+1

你不知道。爲什麼不只是添加一個額外的方法?然後,你的異常的捕手可以說'bad_length.length()'或者其他。 – GManNickG

+0

@GManNickG在這個特殊的問題,我正在解決,預期的輸出只限於'std :: exception :: what()' – Mushy

+0

_I需要使用什麼,因爲我需要使用what_ ok – 2017-10-19 18:27:51

回答

0

你不這樣做。

如果你必須這樣做:

struct custom_error:std::exception { 
    const char* what() const throw() override final { return str.c_str(); } 
    explicit custom_error(std::string s):str(std::move(s)) {} 
    explicit custom_error(int x):custom_error(std::to_string(x)) {} 
private: 
    std::string str; 
}; 

現在我們存儲和返回的序列化描述你的int在緩衝區中,並要求返回一個指針到它。

要轉換回:

int main() { 
    try { 
    throw custom_error(34); 
    } catch (std::exception const& ex) { 
    std::stringstream ss(ex.what()); 
    int x; 
    if (ss >> x) { 
     std::cout << "X is " << x << "\n"; 
    } 
    } 
} 

Live example