【发布时间】:2011-03-29 12:52:46
【问题描述】:
我正在尝试定义一个非常简单的异常类。因为它非常简单,我只想将它保存在 .h 文件中,但编译器不喜欢 throw()。代码:
#include <exception>
#include <string>
class PricingException : public virtual std::exception
{
private:
std::string msg;
public:
PricingException(std::string message) : msg(message) {}
const char* what() const throw() { return msg.c_str(); }
~PricingException() throw() {}
};
GCC 给出以下错误:
/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:13: error: expected unqualified-id before ‘{’ token
/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: expected unqualified-id before ‘{’ token
对于带有throw() 的行。知道如何解决吗?
编辑
我试图删除有问题的方法的主体,即
virtual ~PricingException() throw();// {}
现在我收到更奇怪的错误消息:
/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: looser throw specifier for ‘virtual PricingException::~PricingException()’
/usr/include/c++/4.5/exception:65: error: overriding ‘virtual std::exception::~exception() throw ()’
它只是忽略了我的抛出说明符!
【问题讨论】:
-
使用 gcc 4.2.1 版(Apple Inc. build 5664)在这里编译得很好
-
我正在运行
gcc (Debian 4.5.2-4) 4.5.2 -
您的代码在 gcc 3.4、4.2 和 gcc 4.4 下编译得很好。您是否关闭了一些异常功能?您使用的是旧版本吗?
-
在代码中似乎没有问题。但是为什么你在这里使用虚拟继承呢?
-
可能一个不同的头文件正在使用预处理器重新定义
throw(一个彻底的邪恶做法,但并非闻所未闻)。您可以使用g++ -E查看预处理后的源代码,并检查throw()规范在到达编译器时是否仍然完好。