2013-04-07 77 views
-1

我试图找出如何能够写出这样的事:重载运算符<<用于打印自定义异常

try{ 
    throw MyCustomException; 
} 
catch(const MyCustomException &e){ 
cout<< e; 
} 

但如何界定overloaded operator <<为了这个目的?

自定义异常类:

class MyCustomException{ 

public: 

MyCustomException(const int& x) { 
    stringstream ss; 
    ss << x; 

    msg_ = "Invalid index [" + ss.str() + "]"; 
} 

string getMessage() const { 
    return (msg_); 
} 
private: 
    string msg_; 
}; 
+1

IMO只是'cout << e.getMessage()' – Pubby 2013-04-07 00:33:17

+0

为什么'c'标签? – 2013-04-07 00:33:44

+0

@LightnessRacesinOrbit sry,我的错 – Dworza 2013-04-07 00:35:26

回答

4

老实说,我认为正确的解决办法是遵循标准惯例,使MyCustomExceptionstd::exception派生。然后,您将实现虚拟成员函数what()以返回消息,并最终可以通过operator <<将该字符串插入标准输出。

这是你的异常类会是什么样子:

#include <string> 
#include <sstream> 
#include <stdexcept> 

using std::string; 
using std::stringstream; 

class MyCustomException : public std::exception 
{ 
public: 

    MyCustomException(const int& x) { 
     stringstream ss; 
     ss << x; 
     msg_ = "Invalid index [" + ss.str() + "]"; 
    } 

    virtual const char* what() const noexcept { 
     return (msg_.c_str()); 
    } 

private: 

    string msg_; 
}; 

这里是你将如何使用它:

#include <iostream> 

using std::cout; 

int main() 
{ 
    try 
    { 
     throw MyCustomException(42); 
    } 
    catch(const MyCustomException &e) 
    { 
     cout << e.what(); 
    } 
} 

最后,live example