我可以使用 C 样式转换将派生类转换为私有基类吗? [英] Can I cast a derived class to a private base class, using C-style cast?

查看:21
本文介绍了我可以使用 C 样式转换将派生类转换为私有基类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样做吗?

class A { ... };

class B : private A
{
    const A &foo() const
    {
        return *((const A *)this);
    }
};

我可以将继承自基类的子类转换为基类的公共版本吗?我可以在没有虚拟方法的情况下执行此操作吗?

Can I take a subclass that inherits privately from a base class and cast it to a public version of its base class? Can I do this without it having virtual methods?

我的猜测是肯定的,但我想确保它安全/便携.

My guess is yes, but I wanted to make sure it's safe / portable.

推荐答案

Yes you can: §5.4/7 of the standard:

Yes you can: §5.4/7 of the standard:

... 下面的 static_cast 和 reinterpret_cast 操作(可选后跟 const_cast 操作)可以使用显式类型转换的强制转换表示法,即使基类类型不可访问:

... the following static_cast and reinterpret_cast operations (optionally followed by a const_cast operation) may be performed using the cast notation of explicit type conversion, even if the base class type is not accessible:

指向派生类类型的对象或派生类的左值的指针类类型可以显式转换为指针或引用明确的基类类型,分别;

a pointer to an object of derived class type or an lvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;

但是尽量不要,因为它违背了私有继承的目的.

But try not to as it defeats the purpose of private inheritance.

这篇关于我可以使用 C 样式转换将派生类转换为私有基类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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