[英]Own exception in C++ can not be thrown
我正在嘗試在C ++工作(Linux,g ++)中獲得自定義異常。 Dictionary.hpp
:
#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
拋出異常(這是編譯失敗的地方):
#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();
}
但是我不能編譯它:
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
)編寫異常。
導出自己的異常的一種非常簡單有效的方法是:
struct EDictionaryNoLabel : std::runtime_error
{
using std::runtime_error::runtime_error;
};
而已。
這為您提供了所有標准的構造函數和類型安全性。 另外,如果需要,您可以添加其他方法。
預測:
using std::runtime_error::runtime_error;
做什么? 做?
將基類的構造函數的名稱復制到此類的名稱空間中。 它為您提供了所有基類的構造函數,而無需額外的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.