c++ - runtime_error 中的 string& 与 wstring&

标签 c++ runtime-error

我需要继承 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/

相关文章:

javascript - meteor/javascript 函数在另一个文件中时不起作用

c++ - InterviewStreet 查找字符串

c++ - 制作shader将vertexArray作为canvas而不是window

c++ - 如何在 C++ 中明确数据所有权

sql - Microsoft Access 找不到字段 '|1'

io - 从文件读取期间Fortran运行时错误

c++ - 通过模板函数调用类函数

c++ - 函数成员中的 enable_if 用于 void 和继承

PHP 命名空间未定义函数

error-handling - 如何将 libxml2 xmlParserErrors 代码转换为可打印字符串?