c++ - ';' 标记之前的预期主表达式

标签 c++

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

这是异常的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

有什么问题?

最佳答案

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

throw noimp();

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

关于c++ - ';' 标记之前的预期主表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31495731/

相关文章:

c++ - "//appease MSC"注释中的MSC是什么意思?

c++ - 在主函数中使用类中的数组

c++ - 附加条件语句使程序更快

c++ - c 类型数组的返回迭代器?

c++ - 串行 channel 上的 boost::asio::async_write 问题

c++ - 在VS2008中构建Cuda程序出现问题: LNK2019

c++ - 如何播种随机数生成器?

c++ - 将 constexpr 与 getenv (或替代方案)一起使用

c++ - 使用虚拟基类在 C++ 中向下转型

C++ 模板化工厂构造函数/反序列化