我需要继承 runtime_class
的异常类来接受 wstring&
。这是 MyExceptions.h
:
using namespace std;
class myExceptions : public runtime_error
{
public:
myExceptions(const string &msg ) : runtime_error(msg){};
~myExceptions() throw(){};
};
我希望 myExceptions
像这样接受 wstring&
:myExceptions(const **wstring** &msg )
。但是当我运行它时,我得到了这个错误:
C2664: 'std::runtime_error(const std__string &): cannot convert parameter 1 from 'const std::wstring' to 'const std::string &'
我知道 runtime_error
接受 string&
而不是 wstring&
定义如下 C++ Reference - runtime_error :
> explicit runtime_error (const string& what_arg);
如何在 runtime_error
中使用 wstring&
?
最佳答案
最简单的做法是将常规消息传递给 runtime_error
并直接在 myExceptions
类中处理 wstring 消息:
class myExceptions : public runtime_error {
public:
myExceptions(const wstring &msg ) : runtime_error("Error!"), message(msg) {};
~myExceptions() throw(){};
wstring get_message() { return message; }
private:
wstring message;
};
否则,您可以编写一个从 wstring 转换为 string 的私有(private)静态成员函数,并使用它将转换后的字符串传递给 runtime_error
的构造函数。但是,从this answer可以看出,这不是一件很简单的事情,对于异常构造函数来说可能有点太多了。
关于c++ - runtime_error 中的 string& 与 wstring&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22381488/