正确的方法继承自std :: exception [英] Correct way to inherit from std::exception

查看:114
本文介绍了正确的方法继承自std :: exception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚创建了异常层次结构,并希望将 char * 传递给我的一个派生类的构造函数,并显示一条消息,告诉您有什么问题,但显然 std :: exception 没有可以让我这样做的构造函数。然而,有一个类成员叫做 what(),这将表明可以传递一些信息。

我如何(可以?)传递文本为了传递信息与我的异常类,所以我可以在代码中的某个地方说:

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 happened.");


推荐答案

如果要使用字符串构造函数,您应该继承自 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆