我正在尝试实现异常并将其从我的方法中抛出。
以下是异常
的h
文件
#ifndef EXCEPTION_H
#define EXCEPTION_H
#include <exception>
#include <string>
namespace core {
class no_implementation: public std::exception {
private:
std::string error_message;
public:
no_implementation(std::string error_message);
const char* what() const noexcept;
};
typedef no_implementation noimp;
}
#endif
此处cpp
文件
#include "../headers/exception.h"
using namespace core;
no_implementation::no_implementation(std::string error_message = "Not implemented!") {
this->error_message = error_message;
}
const char* no_implementation::what() const noexcept {
return this->error_message.c_str();
}
这是方法
std::string IndexedObject::to_string() {
throw noimp;
}
但它显示我错误
throw noimp; //expected primary-expression before ';' token
问题是什么?
答案 0 :(得分:6)
要创建一个类型的临时文件,您需要使用这样的符号(请注意额外的括号):
throw noimp();
如果没有括号,则尝试抛出类型而不是对象。除非您将默认值移动到声明中,否则您还将指定字符串:默认情况下需要在使用时显示。
答案 1 :(得分:2)
首先,std::string error_message = "Not implemented!"
之类的默认参数应该放在函数声明中,而不是定义。也就是说,写
...
public:
no_implementation(std::string error_message = "Not implemented!");
...
其次,你抛出的是价值,而不是类型。您已撰写throw noimp;
,但noimp
是类的名称。这应该是throw noimp();
或throw noimp("some message here");
。