2011-08-27 45 views
6

我試圖在Ubuntu下使用g ++編譯如下:試圖從STD繼承時編譯錯誤:: runtime_error

#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 

我有有這個問題一段時間了,我不能真正知道它有什麼問題:/

回答

14

編譯器通過其錯誤消息告訴你重要的事情。如果我們把剛纔的第一個消息(它總是被人照顧的編譯問題之一是好事,通過發生的第一起):

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

它會告訴你看看行9.有在"{"之前的代碼中出現問題:類名稱無效。你可以從中推斷出編譯器可能不知道「std :: runtime_error」是什麼。這意味着編譯器在您提供的頭文件中找不到「std :: runtime_error」。然後你必須檢查你是否包含正確的標題。

在C++參考文檔中快速搜索會告訴您,std :: runtime_error是<stdexcept>標題的一部分,而不是<exception>。這是一個常見的錯誤。

你只需要添加這個頭,錯誤消失了。從其他錯誤消息中,編譯器告訴你幾乎相同的事情,但在構造函數中。

學會閱讀編譯器的錯誤消息是一項非常重要的技巧,目的是爲了避免在編譯問題上被阻塞。

+0

非常感謝日光:D – SlimJim

+0

+1爲父親的建議:) – Chani

6

包括<stdexcept>

+0

我們都在編輯您的簽名。不妨寫下它。節省我們一些麻煩。 _那會很有禮貌。 :-) –

+0

@Tomalak:SO確實有很多幼稚的用戶,我不在乎個人的那部分內容,只是在全球圖景中感到悲傷。 –

+0

幼稚是固執地拒絕接受流行的意見。 :( –

1

您需要有一個完整定義std::runtime_error可用於您從它派生的點。

#include <stdexcept>