我刚刚创建了异常层次结构并想将 char*
传递给我的一个派生类的构造函数,并带有一条消息告诉我出了什么问题,但显然 std::exception
没有允许我这样做的构造函数。然而,有一个名为 what()
的类成员表明可以传递一些信息。
我如何(我可以?)将文本传递给 std::exception
的派生类,以便通过我的异常类传递信息,所以我可以在代码中的某处说:
throw My_Exception("Something bad happened.");
最佳答案
我将以下类用于我的异常,它工作正常:
class Exception: public std::exception
{
public:
/** Constructor (C strings).
* @param message C-style string error message.
* The string contents are copied upon construction.
* Hence, responsibility for deleting the char* lies
* with the caller.
*/
explicit Exception(const char* message)
: msg_(message) {}
/** Constructor (C++ STL strings).
* @param message The error message.
*/
explicit Exception(const std::string& message)
: msg_(message) {}
/** Destructor.
* Virtual to allow for subclassing.
*/
virtual ~Exception() noexcept {}
/** Returns a pointer to the (constant) error description.
* @return A pointer to a const char*. The underlying memory
* is in posession of the Exception object. Callers must
* not attempt to free the memory.
*/
virtual const char* what() const noexcept {
return msg_.c_str();
}
protected:
/** Error message.
*/
std::string msg_;
};
关于c++ - 从 std::exception 继承的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8152720/