2014-03-12 80 views
0

在我的Qt项目,我用这种方式处理多个异常变量:例外c + +显示错误消息

myExceptions.h:

#ifndef MYEXCEPTIONS_H 
#define MYEXCEPTIONS_H 

#include <iostream> 
#include <exception> 
using namespace std; 

class myExceptions : public runtime_error 
{ 

public: 
    myExceptions(const char *msg) : runtime_error(msg){}; 
    ~myExceptions() throw(){}; 

}; 

#endif // MYEXCEPTIONS_H 

我在此呼吁异常在我的代码方法:

abc.cpp

if (!MyClass::aMethod(a, b)) 
{ 
    throw myExceptions("Error message to show"); 

} 

,并抓住它在我的main.cpp:

try { 
     MyClass2 myClass2(param); 
    } catch (myExceptions &e) { 
     QMessageBox::critical(&window, "title", e.what()); 
    } 

在这里没有问题,但是当我想在错误消息中显示变量tmpName的名称时发生。

std::string tmpName; 

else{ 
    throw myExceptions("Unrecognized member : " + &tmpName); 
} 

当我这样做,我得到了以下错误:

C2110:'+' : cannot add two pointers. 

有人可以帮助我,好吗?先谢谢你!

回答

0

删除&throw myExceptions("Unrecognized member : " + tmpName);

这样,你添加一个const char *与为std :: string,而不是试图把两个为const char *。

+0

我想你的意思是 “努力了'为const char *'和*指针*添加到'的std :: string'” ? –

+0

通过这样做,我得到了这个错误: C2440:无法从'std :: basic_string <_Elem,_Traits._Ax>'转换为'myExceptions' – Colet

+0

@Joachim:对,哎呀。 – anderas

0

问题是在下面一行

throw myExceptions("Unrecognized member : " + &tmpName); 

您正在试图为const char *添加到tmpName字符串的地址。 你应该做

tmpName = "Unrecognized member : " + tmpName; 
throw myExceptions(tmpName.c_str()); 

由于您myException类需要const char *作为参数