我正在尝试在 Ubuntu 下用 g++ 编译它:
#ifndef PARSEEXCEPTION_H
#define PARSEEXCEPTION_H
#include<exception>
#include<string>
#include<iostream>
struct ParseException : public std::runtime_error
{
explicit ParseException(const std::string& msg):std::runtime_error(msg){};
explicit ParseException(const std::string& token,const std::string& found):std::runtime_error("missing '"+token+"',instead found: '"+found+"'"){};
};
#endif
我收到错误消息:
In file included from parseexception.cpp:1:
parseexception.h:9: error: expected class-name before ‘{’ token
parseexception.h: In constructor ‘ParseException::ParseException(const std::string&)’:
parseexception.h:10: error: expected class-name before ‘(’ token
parseexception.h:10: error: expected ‘{’ before ‘(’ token
parseexception.h: In constructor ‘ParseException::ParseException(const std::string&, const std::string&)’:
parseexception.h:11: error: expected class-name before ‘(’ token
parseexception.h:11: error: expected ‘{’ before ‘(’ token
enter code here
这个问题我已经有一段时间了,我真的不知道它有什么问题:/
最佳答案
编译器通过它的错误信息告诉你重要的事情。如果我们只处理第一条消息(从出现的第一条消息开始逐条处理编译问题总是一件好事):
parseexception.h:9: error: expected class-name before ‘{’ token
它告诉你看第9行。"{"
之前的代码有问题: 类名无效。您可以由此推断,编译器可能不知道“std::runtime_error”是什么。这意味着编译器在您提供的 header 中找不到“std::runtime_error”。然后,您必须检查是否包含了正确的 header 。
在 C++ 引用文档中快速搜索会告诉您 std::runtime_error 是 <stdexcept>
的一部分 header ,而不是 <exception>
.这是一个常见的错误。
您只需添加此 header ,错误就消失了。从其他错误消息中,编译器告诉您几乎相同的事情,但在构造函数中。
学习阅读编译器的错误消息是一项非常重要的技能,可以避免因编译问题而受阻。
关于c++ - 尝试从 std::runtime_error 继承时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7213362/