Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;异常和从std::exception继承_C++_Exception_Inheritance_Private_Private Inheritance - Fatal编程技术网

C++ C++;异常和从std::exception继承

C++ C++;异常和从std::exception继承,c++,exception,inheritance,private,private-inheritance,C++,Exception,Inheritance,Private,Private Inheritance,给定此示例代码: #include <iostream> #include <stdexcept> class my_exception_t : std::exception { public: explicit my_exception_t() { } virtual const char* what() const throw() { return "Hello, world!"; } }; int main() { tr

给定此示例代码:

#include <iostream>
#include <stdexcept>

class my_exception_t : std::exception
{
public:
    explicit my_exception_t()
    { }

    virtual const char* what() const throw()
    { return "Hello, world!"; }
};

int main()
{
    try
        { throw my_exception_t(); }
    catch (const std::exception& error)
        { std::cerr << "Exception: " << error.what() << std::endl; }
    catch (...)
        { std::cerr << "Exception: unknown" << std::endl; }

    return 0;
}
然而,只要将
my_exception\t
std::exception
public
继承,我就会得到以下输出:

Exception: unknown
Exception: Hello, world!
有人能给我解释一下为什么在这种情况下继承类型很重要吗?标准中参考的奖励积分

有人能给我解释一下原因吗 继承的类型在某种程度上很重要 这个案子?一次旅行的加分 标准中的参考

继承的类型并不重要。重要的是您有一个可访问的转换可用于其中一个catch类型。碰巧的是,由于它不是公共继承,所以没有公共可访问的转换


说明:

您可以在此处看到相同的行为:

class B
{
};

class C1 : B
{
};

class C2 : public B
{
};

int main(int argc, char** argv)
{
    B& b1 = C1();//Compiling error due to conversion exists but is inaccessible
    B& b2 = C2();//OK
    return 0;
}
只有在以下情况下,catch块才会捕获抛出的异常:

  • catch块具有匹配的类型,或
  • catch块用于具有可访问转换的类型
  • catch块是catch(…)

  • 当您以私有方式继承时,您不能转换到或以其他方式访问该类之外的基类。因为您要求标准中的某些内容:

    §11.2/4:
    如果基类的一个虚构的公共成员是可访问的,则称该基类是可访问的。如果基类是可访问的,则可以隐式地将指向派生类的指针转换为指向该基类的指针(4.10、4.11)


    简单地说,对于类之外的任何东西,它就像从未从
    std::exception
    继承一样,因为它是私有的。因此,它将无法被捕获在
    std::exception&
    子句中,因为不存在转换。

    my_exception_t
    在这两种情况下都源自
    std::exception
    。@fbrereto:感谢您的澄清,我在回答中解释过,请重新阅读。