尝试从std :: runtime_error继承时出现编译错误

Sli*_*Jim 6 c++ exception

我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:

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
Run Code Online (Sandbox Code Playgroud)

我现在已经有这个问题了,我真的不知道它有什么问题:/

Nik*_*kko 14

编译器通过其错误消息告诉您重要的事情.如果我们只接受第一条消息(逐个处理编译问题总是一件好事,从发生的第一个开始):

parseexception.h:9: error: expected class-name before ‘{’ token
Run Code Online (Sandbox Code Playgroud)

它告诉你要看第9行.之前的代码中存在一个问题"{":类名无效.您可以从中推断出编译器可能不知道"std :: runtime_error"是什么.这意味着编译器在您提供的标头中找不到"std :: runtime_error".然后,您必须检查是否包含正确的标题.

在C++参考文档中快速搜索将告诉您std :: runtime_error是<stdexcept>标题的一部分,而不是<exception>.这是一个常见的错误.

然后你必须添加这个标题,错误消失了.从其他错误消息中,编译器会告诉您几乎相同的内容,但是在构造函数中.

学习阅读编译器的错误消息是一项非常重要的技能,以避免在编译问题上被阻止.


Che*_*Alf 6

包括<stdexcept>.