2012-02-13 50 views
1

我有一類從std::runtime_error繼承像這樣:如何修改C++ runtime_error的字符串?

#include <string> 
#include <stdexcept> 

class SomeEx : public std::runtime_error 
{ 
public: 
    SomeEx(const std::string& msg) : runtime_error(msg) { } 
}; 

所述msg總是會像「無效類型ID 43」。有什麼辦法與另一個構造函數(或另一種方法)構建「什麼字符串」,以便我只提供整數類型ID?喜歡的東西:

SomeEx(unsigned int id) { 
    // set what string to ("invalid type ID " + id) 
} 

回答

4
static std::string get_message(unsigned int id) { 
    std::stringstream ss; 
    ss << "invalid type ID " << id; 
    return ss.str(); 
} 
SomeEx(unsigned int id) 
    : runtime_error(get_message(id)) 
{} 

無關:我們之所以有串.what()是讓人們停止使用錯誤號碼。

2

肯定的:SomeEx(unsigned int id) : runtime_error(std::to_string(id)) { }

0

如果您可以將數字轉換成字符串,那麼你可以簡單地添加他們:

#include <string> 
#include <stdexcept> 

std::string BuildMessage(std::string const& msg, int x) 
{ 
    std::string result(msg); 

    // Build your string here 
    return result; 
} 

class SomeEx : public std::runtime_error 
{ 
    public: 
     SomeEx(const std::string& msg) 
      : runtime_error(BuildMessage(msg, id)) { } 
};