#include <iostream>
class c1{
};
class c2{
};
int main(){
c1 a;
c2 b;
//b = static_cast<c2>(a); <-- will not compile
b = *reinterpret_cast<c2*>(&a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
b = static_cast<c2>(a); 不会编译出现此错误:
no matching conversion for static_cast from 'c1' to 'c2'
Run Code Online (Sandbox Code Playgroud)
使用reinterpret_cast和做 abit cast是实现这一目标的唯一方法吗?
正确的方法是提供一种将一种转换为另一种的方法。有不同的方法可以做到这一点,这是一种方法:
struct c2;
struct c1{
explicit operator c2 ();
};
struct c2{ };
c1::operator c2() { return {};}
int main(){
c1 a;
c2 b;
b = static_cast<c2>(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果你坚持“无关”...
在 C++ 中将对象转换为不相关对象的正确方法是什么
空无一人。
reinterpret_cast是使编译器静音的好方法,但它b = *reinterpret_cast<c2*>(&a);是未定义的行为。人们通常reinterpret_cast认为它是一个神奇的任意对任意类型的演员,但事实并非如此。有关定义的案例的相当有限的列表,请参见此处。不相关类型的对象之间的转换不在列表中。