2016-04-01 22 views
1

C++でカスタム例外を取得しようとしています(Linux、g ++)。 Dictionary.hppC++で独自の例外をスローできません

#include <map> 
#include <string> 
#include "Dictionary.hpp" 

using namespace std; 

// map<string, string> dictMap; 
Dictionary::Dictionary() { 
} 

void Dictionary::update(string label, string value) { 
     dictMap[label]=value; 
} 

string Dictionary::read(string label){ 
     if (0==dictMap.count(label)) { 
       throw(EDictionaryNoLabel("label not found")); 
     } 
     return dictMap[label]; 
} 

void Dictionary::refresh() { 
     dictMap.clear(); 
} 

しかし、私はそれをコンパイルすることはできません:

#ifndef HEADER_DICTIONARY_H 
#define HEADER_DICTIONARY_H 

#include <map> 
#include <string> 
#include <stdexcept> 

using namespace std; 

[...] 

class EDictionaryNoLabel : public runtime_error 
{ 
public: 
      explicit EDictionaryNoLabel(const string& __arg); 
      virtual ~EDictionaryNoLabel() _GLIBCXX_USE_NOEXCEPT; 
}; 

#endif 

そしてDictionary.cppに、私は例外をスロー(コンパイルが失敗したのはここです)

utils/Dictionary.o: In function `Dictionary::read(std::string)': 
Dictionary.cpp:(.text+0xbf): undefined reference to `EDictionaryNoLabel::EDictionaryNoLabel(std::string const&)' 
Dictionary.cpp:(.text+0xdc): undefined reference to `EDictionaryNoLabel::~EDictionaryNoLabel()' 
Dictionary.cpp:(.text+0xe1): undefined reference to `typeinfo for EDictionaryNoLabel' 
/tmp/ccXT7dWk.o:(.gcc_except_table+0x68): undefined reference to `typeinfo for EDictionaryNoLabel' 
collect2: error: ld returned 1 exit status 
make: *** [Test] Error 1 

は、私は私の例外を書きます正確に標準 overflow_error(これも runtime_errorから継承)と同じです。

+4

例外のコンストラクタデストラクタの定義はどこですか? –

+0

πάνταῥεthankありがとうございます。 '' 'runtime_error'''から継承したコンストラクタとデストラクタはありませんか?私は特別な振る舞いは必要ありません。新しい例外が必要です。 – LiPo

+0

いいえ、コンストラクタ/デストラクタは実装なしで継承することはできません。クラスごとに一意に指定する必要があります。基本クラスのコンストラクタは、実装のメンバ初期化子リストで指定できます。 –

答えて

2

独自の例外を導き出すために非常に簡単で効果的な方法は次のとおりです。それだけです

struct EDictionaryNoLabel : std::runtime_error 
{ 
    using std::runtime_error::runtime_error; 
}; 

これは、すべての標準コンストラクタと型安全性を提供します。さらに、必要に応じてメソッドを追加することもできます。

見込ん:

using std::runtime_error::runtime_error;は何をしますか?

は、このクラスの名前空間に基本クラスのコンストラクタの名前をコピーします。それはあなたに余分なコードなしですべての基本クラスのコンストラクタを提供します。

+0

ありがとうございます。多くの言語を使用して長年にわたってプログラミングを行ってきたので、例外処理のために多くの時間を費やすのは非常に不満です。あなたは非常にコンパクトであるので、あなたのソリューションは素晴らしいです。構造体とクラスの接続は驚くべきことです。 – LiPo

+0

@LiPo in C++ structとクラスは、structがデフォルトでpublicであり、デフォルトでpublicに継承されている点を除いて同じです。ほとんどのクラスはパブリックコンストラクタを必要とし、ほとんどの派生クラスは基本クラスのインタフェースを公開する必要があるため、誰もキーワード 'class'を全く使用しないことに驚いています。それはちょうど私がタイプする努力の浪費のように思える。 –

関連する問題