gpt4 book ai didi

c++ - C++中自己的异常不能抛出

转载 作者:行者123 更新时间:2023-11-30 03:43:05 24 4
gpt4 key购买 nike

我正在尝试在 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;
};

就是这样。

这为您提供了所有标准构造函数和类型安全。另外,如果需要,您可以添加更多方法。

期待:

What does using std::runtime_error::runtime_error; do?

将基类构造函数的名称复制到此类的命名空间中。它为您提供了所有基类的构造函数,无需额外代码。

关于c++ - C++中自己的异常不能抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36359398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com