gpt4 book ai didi

c++ - 可以编写 catch() 以从一种对象类型转换为另一种对象类型吗?

转载 作者:太空狗 更新时间:2023-10-29 19:58:57 27 4
gpt4 key购买 nike

给定这段代码,其中 A 在第 3 方库中,B 是我编写的代码:

class A {...};
class B { public: B( const A &a ); ... };

try
{
A a(...);
throw a;
}
catch ( const B &b )
{
// ...do stuff with B, like log the details to a file...
}

如果一个对象 A 被抛出,那么我的 catch B 就会被跳过。我希望因为 B 有一个接受 A 对象的构造函数,所以这可能会起作用。

我可以做些什么来完成这项工作,还是我必须修改所有 catch 子句以处理同时捕获 AB?

最佳答案

不,那行不通。将抛出的对象与处理程序匹配时,不考虑用户定义的转换。根据 C++11 标准的第 15.3/3 段:

A handler is a match for an exception object of type E if

  • The handler is of type cv T or cv T& and E and T are the same type (ignoring the top-level cv-qualifiers), or

  • the handler is of type cv T or cv T& and T is an unambiguous public base class of E, or

  • the handler is of type cv T or const T& where T is a pointer type and E is a pointer type that can be converted to T by either or both of

    • a standard pointer conversion (4.10) not involving conversions to pointers to private or protected or ambiguous classes

    • a qualification conversion

  • the handler is of type cv T or const T& where T is a pointer or pointer to member type and E is std::nullptr_t.

关于c++ - 可以编写 catch() 以从一种对象类型转换为另一种对象类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16325772/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com