【发布时间】: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
它有效,但我不确定我是否在这里得到某种UB。也许有人可以参考标准?
我提供了这种情况,因为我有两个类(B、C)并且在某些模块中我只需要使用B 的一部分功能(C 的功能)。但是我已经实例化了B类,我可以像我一样做reinterpret_cast吗?
【问题讨论】:
-
为什么不直接将
B*隐式转换为A*? -
@Fireho 其实我有更复杂的例子。我提供这个例子只是为了确保它是否可以完成......