我试图在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"是什么。这意味着编译器不会在您提供的头文件中找到"std::runtime_error"。然后你必须检查你是否包含了正确的标题。
在c++参考文档中快速搜索一下,你会发现std::runtime_error是<stdexcept>
头的一部分,而不是<exception>
。这是一个常见的错误。
你只需要添加这个标题,错误就消失了。从其他错误消息中,编译器告诉您的内容大致相同,但在构造函数中。
为了避免在编译问题上受阻,学习阅读编译器的错误信息是一项非常重要的技能。
include <stdexcept>
你需要有一个完整的std::runtime_error
的定义,在你从它得到的点。
#include <stdexcept>