c – 异常多重继承
作者:互联网
我有混合异常和多重继承的问题.基本上我有这个代码:
#include <exception>
#include <stdexcept>
#include <iostream>
class A : public std::exception
{
public:
virtual ~A() noexcept {};
};
class B : public A, public std::runtime_error
{
public:
B() : A{}, std::runtime_error{""}
{
}
};
int main()
{
try {
throw B{};
} catch (const std::exception& error) {
// this catch doesn't work
std::clog << "Caught!" << std::endl;
}
}
我需要修改它,以便可以将类B的异常捕获为std :: exception(现在调用终止处理程序).我怎样才能实现这种行为?我想虚拟继承是必需的,但在这种情况下我没有看到任何使用它的方法.
更新:我需要能够:
– 抓A作为A(琐碎),
– 捕获A作为std :: exception,
– 将B记为B(再次,琐碎),
– 将B捕获为std :: exception,
– 将B捕获为std :: runtime_error
我知道这是很多要求,也许它没有多大意义,但我需要它,我只是好奇:)
UPDATE2:我认为问题是std :: runtime_error几乎没有从std :: exception中获取(这将允许我通过A中的虚拟继承来解决问题).我对吗?还是,可以解决吗?
更新3:Alan Stokes在下面的评论中提出了解决方案,这似乎对我有用:
Can you split A into two classes – one that implements the functionality B needs, and one that adds in the inheritance from std::exception? Then both A and B could inherit from (say) A_base.
谢谢你,如果有人有其他好的解决方案,请告诉我.
解决方法:
Stroustrup建议虚拟地从std :: exception继承,因此只有一个转换路径.
就个人而言,我发现制定一个多继承方案可能是过度工程化的,而更喜欢线性继承链……或者根本就没有.
标签:c,exception-handling,inheritance,multiple-inheritance 来源: https://codeday.me/bug/20191001/1838202.html