我正在尝试在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;
办?
将基类的构造函数的名称复制到该类的名称空间中。它为您提供了所有基类的构造函数,而无需任何额外的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句