如何从std :: runtime_error继承?

时间:2013-05-13 00:03:03

标签: c++ inheritance runtime-error

例如:

#include <stdexcept>
class A { };
class err : public A, public std::runtime_error("") { };
int main() {
   err x;
   return 0;
}

("") runtime_error之后的error: expected '{' before '(' token error: expected unqualified-id before string constant error: expected ')' before string constant

("")

其他(没有In constructor 'err::err()': error: no matching function for call to 'std::runtime_error::runtime_error()' )我

{{1}}

出了什么问题?

(您可以在此处测试:http://www.compileonline.com/compile_cpp_online.php

2 个答案:

答案 0 :(得分:16)

这是正确的语法:

class err : public A, public std::runtime_error

而不是:

class err : public A, public std::runtime_error("")

正如你上面所做的那样。如果要将空字符串传递给std::runtime_error的构造函数,请按以下方式执行:

class err : public A, public std::runtime_error
{
public:
    err() : std::runtime_error("") { }
//        ^^^^^^^^^^^^^^^^^^^^^^^^
};

这是显示代码编译的live example

答案 1 :(得分:0)

想补充一点,或者 err 类可以接受一个字符串消息并将其简单地转发到 std::runtime_error,或者默认情况下是一个空字符串,如下所示:

#pragma once

#include <stdexcept>

class err : public std::runtime_error
{
public:
    err(const std::string& what = "") : std::runtime_error(what) {}
};
相关问题