gpt4 book ai didi

c++ - 私有(private)继承、友元和异常处理

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:57:52 26 4
gpt4 key购买 nike

当A类私有(private)继承自B类时,意味着B是A的私有(private)基类子对象。但对 friend 来说不是,对 friend 来说是公共(public)子对象。当有多个 catch 处理程序时,第一个匹配的处理程序(即,如果异常类型可以隐式转换为处理程序的参数类型)被调用。那么有人会向我解释为什么下面的代码不能像我预期的那样工作吗?此行为是标准有意为之还是 MSVC 错误?

class A
{
};
class B:A //private inheritance
{
friend void g();
};

void f()
{

B b;
//A* pa = &b; // error, conversion exists, but is inaccessible
throw b;
}

void g()
{
B b;
A* pa = &b; //ok, private inheritance, but g() is B's friend so it is as though public
try
{
f();
}
catch(A&)
{
//WHY ISN'T THIS HANDLER INVOKED?! B&->A& conversion exists in this function
}
catch(B&)
{
}
}

int main()
{
g();
}

附言这不是真正的代码,这是一个理论实验,也就是说,不要告诉我 friend 不好,组合优于私有(private)继承等。

提前致谢

最佳答案

不,标准不是这么说的。它说(C++0x):

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 cv1 T* cv2 and E is a pointer type that can be converted to the type of the handler 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 a pointer or pointer to member type and E is std::nullptr_t

基本原理:实现复杂。您可以将此视为转换发生在 throw 和 catch 之间的某处,而不是 g 本身。

关于c++ - 私有(private)继承、友元和异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3899563/

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