开发者

compile-error when trying to inherit from std::runtime_error

I'm trying to compile this with g++ under Ubuntu:

#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

I get the error-message:

In file included from parseexception.cpp:1:
parseexception.h:9: error: expected class-name before ‘{’ token
parseexception.h: In construct开发者_开发百科or ‘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

I have had this problem for sometime now and I can't really se whats wrong with it :/


The compiler through its error messages tells you important things. If we take just the first message (it is always a good thing to take care of compilation problems one by one, starting by the first that occurred):

parseexception.h:9: error: expected class-name before ‘{’ token

It tells you to look at line 9. There is a problem in the code just before "{" : the class name is invalid. You can deduce from this that the compiler may not know what "std::runtime_error" is. This means that the compiler does not find "std::runtime_error" in the headers you provided. You then have to check if you have included the correct headers.

A quick search in a C++ reference documentation will tell you that std::runtime_error is part of the <stdexcept> header, not <exception>. That's a common mistake.

You just then have to add this header and the error is gone. From the other error messages, the compiler tells you just about the same things, but in the constructors.

Learning to read the compiler's error messages is a very important skill in order to avoid being blocked on compilation problems.


include <stdexcept>.


You need to have a full definition of std::runtime_error available at the point you derive from it.

#include <stdexcept>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜