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 样式转换将派生类转换为私有基类吗?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
