";"标记之前的预期主表达式

expected primary-expression before ';' token

本文关键字:表达式      更新时间:2023-10-16

我正在尝试实现异常并将其从我的方法中抛出。

下面是异常

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 file

#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

有什么问题吗?

要创建一个临时类型,您需要使用这样的符号(注意额外的括号):

throw noimp();

如果没有括号,则尝试抛出类型而不是对象。除非您将默认值移到声明中,否则您还需要指定字符串:默认值在使用时需要可见。

首先,默认参数(如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");