考虑以下示例:
#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
它有效,但我不确定我是否在这里得到了某种 UB
。也许有人可以引用标准?
我提供这种情况是因为我有两个类(B
、C
)并且在某些模块中我只需要使用 B
的一部分> 的功能(C
的功能)。但是我已经实例化了 B
类,我可以像我一样制作 reinterpret_cast
吗?
最佳答案
这不是 reinterpret_cast 的目的。
大多数在线文档都有类似于
的免责声明Misuse of the reinterpret_cast operator can easily be unsafe. Unless the desired conversion is inherently low-level, you should use one of the other cast operators.
The reinterpret_cast operator can be used for conversions such as char* to int*, or One_class* to Unrelated_class*, which are inherently unsafe.
此节选自MSDN .强调我的。
关于c++ - 转换为具有相同基数 : 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448033/