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
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01