正确的方法继承自std :: exception [英] Correct way to inherit from std::exception
问题描述
我刚刚创建了异常层次结构,并希望将 char *
传递给我的一个派生类的构造函数,并显示一个消息告诉错误,但显然 std :: exception
没有构造函数允许我这样做。然而,有一个类成员 what()
,这将建议一些信息可以传递。
我如何(我可以?)传递文本到一个 std :: exception
的派生类为了传递信息与我的异常类,所以我可以说在代码中的某处:
I've just created exception hierarchy and wanted to pass char*
to constructor of one of my derived classes with a message telling what's wrong, but apparently std::exception
doesn't have constructor which would allow me to do so. Yet there is a class member called what()
which would suggest that some information can be passed.
How can I (can I?) pass text to derived class of a std::exception
in order to pass info with my exception class, so I can say somewhere in the code:
throw My_Exception("Something bad happend.");
推荐答案
如果你想使用字符串构造函数,您应该继承 std :: runtime_error 或 std :: logic_error ,它实现了一个字符串构造函数并实现了std :: exception :: what方法。
If you want to make use of the string constructor, you should inherit from std::runtime_error or std::logic_error which implements a string constructor and implements the std::exception::what method.
然后它只是一个从你的新继承类调用runtime_error / logic_error构造函数的情况,或者如果你使用c ++ 11,你可以使用构造函数继承。
Then it's just a case of calling the runtime_error/logic_error constructor from your new inherited class, or if you're using c++11 you can use constructor inheritance.
这篇关于正确的方法继承自std :: exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!