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

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

问题描述

我可以这样做吗?

  class A {...} 

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

我可以从子类继承一个子类,并将其转换为它的公共版本基类?我可以在没有虚拟方法的情况下这样做吗?



我的猜测是肯定的,但我想确保它是安全的/可移植的。


<是的,您可以:§5.4/ 7的标准:


...下面的static_cast和reinterpret_cast操作
(可选地后跟一个const_cast操作)可以使用
执行显式类型转换的转换符号,即使基类
类型不可访问:



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


但是,请尝试不要,因为它违背了私人继承的目的。


Can I do this?

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:

... 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天全站免登陆