Can I cast a derived class to a private base class, using C-style cast?(我可以使用 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 样式转换将派生类转换为私有基类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以使用 C 样式转换将派生类转换为私有基类吗?
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01