【问题标题】:Exceptions C++ show a variable in the error message异常 C++ 在错误消息中显示变量
【发布时间】:2014-04-16 10:40:54
【问题描述】:

在我的 Qt 项目中,我以这种方式处理多个异常:

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.

有人可以帮帮我吗?提前谢谢!

【问题讨论】:

    标签: c++ qt exception pointers


    【解决方案1】:

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

    这样,您添加了一个 const char* 和一个 std::string,而不是尝试添加两个 const char*。

    【讨论】:

    • 我想你的意思是“试图添加一个const char * 和一个指针std::string”?
    • 这样做,我得到了这个错误:C2440: cannot convert from 'std::basic_string<_elem>' to 'myExceptions'
    • Colet:如果您在myExceptions 构造函数中将参数msg 声明为const std::string&amp; 类型,那么一切正常。
    【解决方案2】:

    问题在下面一行

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

    您正在尝试将 const char * 添加到 tmpName 字符串的地址。 你应该这样做

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

    由于您的 myException 类将 const char * 作为参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多