我有一个C类,我试图在Ubuntu中运行它:
- #ifndef WRONGPARAMETEREXCEPTION_H_
- #define WRONGPARAMETEREXCEPTION_H_
- #include <iostream>
- #include <exception>
- #include <string>
- using namespace std;
- #pragma once
- class WrongParameterException: public exception
- {
- public:
- WrongParameterException(char* message): exception(message) {};
- virtual ~WrongParameterException() throw() {};
- };
- #endif
当我尝试编译它,编译器给我这个错误:
- WrongParameterException.h: In constructor ‘WrongParameterException::WrongParameterException(char*)’:
- WrongParameterException.h:14: error: no matching function for call to ‘std::exception::exception(char*&)’
- /usr/include/c++/4.3/exception:59: note: candidates are: std::exception::exception()
- /usr/include/c++/4.3/exception:57: note: std::exception::exception(const std::exception&)
有谁能告诉我我做错了什么?我尝试将消息变量更改为string或const string或const string&但它没有帮助.
这是我如何使用我从main创建的新异常:
- try
- {
- if ((strToInt1 == -1) || (parameters[1] == NULL) || (strToInt3 == -1) || (parameters[3] != NULL))
- {
- throw WrongParameterException("Error in the config or commands file");
- }
- }
- catch(WrongParameterException e)
- {
- log.addMsg(e.what());
- }
解决方法
首先,#pragma一次是错误的方法,了解标题包括守卫.
Related question on SO解释了为什么使用#pragma一次是错误的方法.维基百科解释如何使用
include guards服务于相同的目的而没有任何缺点.
其次,您使用不知道的参数调用std :: exception的构造函数,在这种情况下是指向字符数组的指针.
- #include <stdexcept>
- #include <string>
- class WrongParameterException : public std::runtime_error {
- public:
- WrongParameterException(const std::string& message)
- : std::runtime_error(message) { };
- };
可能是你想要的有关例外的更多信息,请查看c00plus.com的C++ FAQ Lite article on Exceptions和exceptions article.
祝你好运!