【问题标题】:Casting to the class with the same base:投射到具有相同基础的类:
【发布时间】:2015-06-09 11:29:36
【问题描述】:

考虑以下示例:

#include <iostream>

struct A{ void foo(){ std::cout << "foo()" << std::endl; } };

struct D{ void bar(){ std::cout << "bar()" << std::endl; } };

struct B : A, D{ };

struct C : A{ };

B *b = new B();

C *c = reinterpret_cast<C*>(b);

int main(){ c -> foo(); } //prints foo

DEMO

它有效,但我不确定我是否在这里得到某种UB。也许有人可以参考标准?

我提供了这种情况,因为我有两个类(BC)并且在某些模块中我只需要使用B 的一部分功能(C 的功能)。但是我已经实例化了B类,我可以像我一样做reinterpret_cast吗?

【问题讨论】:

  • 为什么不直接将B* 隐式转换为A*
  • @Fireho 其实我有更复杂的例子。我提供这个例子只是为了确保它是否可以完成......

标签: c++ casting


【解决方案1】:

这不是 reinterpret_cast 的目的。

大多数在线文档都有类似的免责声明

误用 reinterpret_cast 操作符很容易导致不安全。除非 所需的转换本质上是低级的,您应该使用其中之一 其他演员。

reinterpret_cast 运算符可用于转换,例如 char* 到 int*,或 One_class* 到 Unrelated_class*,它们本质上是 不安全

这段摘录来自MSDN。强调我的。

【讨论】:

  • 那么,如果没有 UB,甚至不可能执行这样的转换,是吗?
  • 不,不是按照规定的方式。 B 和 C 无关。不过,您可以进行实际转换。
  • 你的意思是显式转换,是吗?
  • 确实如此。转换函数C* convert(B* original);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多