【发布时间】:2013-12-30 04:26:17
【问题描述】:
我正在尝试编写一个用于处理异常的类。我认为添加一个
class prc_exception : public std::exception {
private:
int line_num;
std::ostringstream* msg;
public:
prc_exception(const char* part, const int line) throw()
: exception() {
msg = new std::ostringstream();
*msg << "<parcer:" << part << ":" << line << ">: ";
}
~prc_exception() throw() { delete msg; }
virtual const char* what() const throw() { return msg->str().c_str(); }
virtual const int line() const throw() { return line_num; }
template <class T> prc_exception& operator<<(const T& rhs)
{ *msg << rhs; return (*this); }
};
另外,如果有人可以提出更好的方法来处理我想做的事情,请给我一个建议。 我想要的是这样可用的东西:
throw prc_exception("code_part",__LINE__) << "More info";
当被捕获时它的 what() 函数会返回一个字符串,如:
<parcer:code_part:36>: More info
非常感谢。
已解决: 正如@polkadotcadaver 建议的那样,添加一个复制构造函数和一个复制赋值运算符解决了这个问题。固定代码按预期运行: #包括 #包括
using namespace std;
class prc_exception : public std::exception {
private:
int line_num;
std::ostringstream msg;
public:
prc_exception(const char* part, const int line) throw()
: exception() {
msg << "<parcer:" << part << ":" << line << ">: ";
}
/** Copy Constructor */
prc_exception (const prc_exception& other)
{
line_num = other.line();
msg << other.what();
}
/** Copy Assignment Operator */
prc_exception& operator= (const prc_exception& other)
{
line_num = other.line();
msg << other.what();
return *this;
}
~prc_exception() throw() { }
virtual const char* what() const throw() { return msg.str().c_str(); }
virtual const int line() const throw() { return line_num; }
template <class T> prc_exception& operator<<(const T& rhs)
{ msg << rhs; return (*this); }
};
int main()
{
try
{
throw prc_exception("hello", 5) << "text." << " more text.";
} catch (exception& e) {
cout << e.what() << endl;
}
return 0;
}
【问题讨论】:
-
查看copy-and-swap idiom,了解在这种情况下如何编写复制赋值运算符(注意,我没试过!)
标签: c++ class exception stream destructor