(C++)在单独的文件中创建 std::expection 类时,输入错误末尾的预期"{"

(C++) Expected '{' at end of an input error while creating std::expection class in separate files

本文关键字:错误 输入 C++ 类时 文件 单独 创建 expection std      更新时间:2023-10-16

我需要创建自己的类,该类继承自std::exception。我需要在单独的文件中执行此操作。我使用了讲座中提供的例子,问题是它显示在一个.cpp文件中,一旦它被拆分,我就会得到一个错误。我该怎么修?

RzymArabException.h文件:(这是我在第11行得到错误的地方)

#ifndef RZYMARABEXCEPTION_H_INCLUDED
#define RZYMARABEXCEPTION_H_INCLUDED
#include <string>
#include <exception>
using namespace std;
class RzymArabException: public exception {
private:
    string s;
public:
    RzymArabException(string ss) : s(ss);
    virtual ~RzymArabException() throw();
    virtual const char* what() const throw();
};
#endif // RZYMARABEXCEPTION_H_INCLUDED

RzymArabException.cpp:

#include "RzymArabException.h"
#include <iostream>
#include <exception>
#include <string>
using namespace std;
RzymArabException(string ss) : s(ss) {}
virtual ~RzymArabException() throw() {}
virtual const char* what() const throw() {
    return s.c_str();
}

错误是由于您有一个构造函数初始化列表,但这里没有格式良好的构造函数定义:

RzymArabException(string ss) : s(ss);

如果要在.cpp中实现构造函数,请在标头中正确声明:

RzymArabException(string ss);

请注意,异常规范已被弃用,因此我已将它们从下面的代码中删除。

您的下一个问题是,成员定义都需要在RzymArabException范围内:

//RzymArabException.cpp
RzymArabException::RzymArabException(string ss) : s(ss) {}
RzymArabException::~RzymArabException() {}
const char* RzymArabException::what() const {
    return s.c_str();
}