C型上升和下降涉及私人继承 [英] C-Style upcast and downcast involving private inheritance

查看:109
本文介绍了C型上升和下降涉及私人继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码: -

Consider the following piece of code :-

class A {};

class B : private A {};

B* bPtr1 = new B;
// A* aPtr1 = bPtr1; // error
// A* aPtr2 = static_cast<A*>(bPtr1); // error
A* aPtr3 = (A*)bPtr1;
B* bPtr2 = (B*)aPtr3;

C风格的转换会丢弃私有继承,而隐式和 static_cast fail(也 dynamic_cast )。为什么?
如果C风格的转换只是bit-fiddling,C ++转换如何实现,即它们如何知道从内存占用的继承类型?

The C-style cast discards the private inheritance while both the implicit and static_cast fail (also dynamic_cast). Why ? If C-style casts are just bit-fiddling, how are C++ casts implemented i.e. how do they know the type of inheritance from memory footprint?

bPtr1被转换为一个Ptr3,我将不得不使用另一个C风格的转换到B再次 static_cast dynamic_cast 失败。

After bPtr1 is casted to aPtr3, i will have to use another C-style cast to downcast to B as again both static_cast and dynamic_cast fail. So, is bPtr2 guaranteed to be good?

推荐答案

p> 5.4.7中的标准状态,C风格的转换实际上可以比任何新风格的转换可以做的更多 - 具体包括从指针到派生指针转换,即使基类是不可访问的,这正是这里发生的私有继承。 (为什么应该允许,特别是为什么它应该只允许C风格的演员,这完全超出了我的意思,但它是不可否认的允许的。)

The standard states in 5.4.7 that C-style casts can actually do more than any sequence of new-style casts can do -- specifically including casting from a pointer-to-derived to pointer-to-base even when the base class is inaccessible, which is precisely what happens here with private inheritance. (Why this should be allowed, and in particular why it should be allowed only for C-style casts, is utterly beyond me; but it's undeniably allowed.)

是正确的,即使 B 从多个基类继承,编译器也必须正确处理OP的C风格指针转换。我自己用MSVC ++ 8和MinGW测试证实了他的实践结果 - 当 B 从多个基类继承时,编译器将调整指针转换 B * A * ,反之亦然,以便识别正确的对象或子对象。

So dribeas is right, compilers are obliged to handle the OP's C-style pointer conversion correctly, even when B inherits from multiple base classes. My own testing with MSVC++8 and MinGW confirms his results in practice -- when B inherits from multiple base classes, the compiler will adjust pointers when converting a B* to an A* or vice versa so that the correct object or subobject is identified.

我坚持我应该从 A 公开得到 B $ c>如果您打算将 B 视为 A ,因为使用私有继承而不是 使用C风格的Cast。

I stand by my assertion that you ought to derive B publicly from A if you ever intend to treat a B as an A, since using private inheritance instead necessitates using C-style casts.

这篇关于C型上升和下降涉及私人继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆