为什么不允许这种交叉广播?
Why is this cross-cast not allowed?
考虑这个简单的例子:
struct Base1 {};
struct Base2 {};
struct Derived : public Base1, public Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = static_cast<Base2*>(foo1);
}
我得到:
Error: static_cast from 'Base1 *' to 'Base2 *', which are not related by inheritance, is not allowed
编译器应该有足够的信息来弄清楚Base2
可以在没有 RTTI (dynamic_cast
( 的情况下从Derived
访问,并让我做:
Derived* foo3 = static_cast<Derived*>(foo1);
Base2* foo2 = foo3;
为什么不允许这样做?(有人可能会争辩说,编译器不知道foo1
是否属于Derived
类型,但static_cast
即使在从Base1
转换为Derived
时也不会检查该类型(
注意:这个问题与我的类似,但并不完全相同,因为这里我们是交叉转换基类,而不是派生的
static_cast
会失败,因为非正式地说,Base1
和Base2
是不相关的。
但是,如果您的类是多态的,则dynamic_cast
将起作用:您可以通过添加虚拟析构函数来实现:
struct Base1 {virtual ~Base1() = default;};
struct Base2 {virtual ~Base2() = default;};
struct Derived : Base1, Base2 {};
int main()
{
Derived foo;
Base1* foo1 = &foo;
Base2* foo2 = dynamic_cast<Base2*>(foo1);
}
这种从Base1
到Base2
的转换在使用组合(即接口(时是惯用的。
相关文章:
- 为什么 Clang 不允许"and"作为函数名称?
- 不允许在向量中添加更多元素
- std::带有自定义缓冲区的 iostream 不允许我写入
- Visual Studio 2017 不允许我创建 C++ 专用模板
- 返回时不允许隐式转换
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么 c++ 不允许(自动)强制转换?
- 为什么 c++11 不允许使用自动
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 为什么不允许使用可变长度数组作为向量元素?
- 余数除法和不允许除以零 (c++) 时遇到问题
- C++从外部类继承的嵌套类;不允许使用不完整的类型
- 在 c++ 中三元运算符中不允许继续(关键字)吗?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?
- 错误:在第 6 行'{'标记之前,此处不允许使用函数定义
- 不允许在类定义之外重写
- 不允许运算符 const 参数调用 const 成员函数
- E0322:不允许使用抽象类类型 " " 的对象
- error dllimport 函数的定义不允许在一个特定的联合中,而其他类、结构和联合将按预期导出
- 为什么不允许这种交叉广播?