自定义异常类C ++

时间:2015-01-07 13:28:43

标签: c++

我会写一个自定义异常类,但这是不可能的,因为我有一个错误。

SSException.h:

#ifndef SSEXCEPTION_H
#define SSEXCEPTION_H

#include <iostream>
#include <exception>

class SSException: public std::exception {

public :
    virtual const char* what() const throw();

private:
    const char* errMessage_;

};

#endif

SSException.cpp:

using namespace std;

const char* SSException::what() const throw()
{
    return "UNKNOW";
}

我会有一个自定义方法,例如: virtual const char * getMsg(int code);

但是这个解决方案不起作用。你能帮助我吗 ? 实现:

try {
   st.timeRef();
    }   catch(const SSException& ex)    {
        //cerr << "Solar System Exception: \n" << ex.what() << endl;
        cerr << "Solar System Exception: \n" << ex.getMsg(2) << endl;
    }

错误:

  

SolarSystem.cpp:26:54:错误:将'const SSException'传递为'this'   'virtual const char * SSException :: getMsg(int)'的参数丢弃   限定符[-fpermissive] cerr&lt;&lt; “太阳系异常:\ n”&lt;&lt;   ex.getMsg(2)&lt;&lt; ENDL;

提前谢谢

1 个答案:

答案 0 :(得分:5)

  

我会有一个自定义方法,例如:virtual const char * getMsg(int code);

它需要virtual const char* getMsg(int code) const;,因为您的代码会通过常量引用捕获。 在这种情况下,const只表示函数getMsg不会修改其对象。

相关问题