【发布时间】:2021-07-30 19:27:14
【问题描述】:
#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;
}
b = static_cast<c2>(a); 将不会编译并出现此错误:
no matching conversion for static_cast from 'c1' to 'c2'
使用reinterpret_cast 并执行bit cast 是实现此目的的唯一方法吗?
【问题讨论】:
-
没有尝试过
bit_cast,因为它是 C++20,但它们应该是唯一的方法。可能相关:C++20 bit_cast vs reinterpret_cast -
你为什么不使用
union? -
@Ranoiaetep 我的意思是我正在使用上面的
reinterpret_cast进行手动位转换,这也是一种位转换。 -
您可能需要考虑 - "...每当尝试通过 AliasedType 类型的 glvalue 读取或修改 DynamicType 类型的对象的存储值时,行为是未定义的除非满足以下条件之一:..." en.cppreference.com/w/cpp/language/reinterpret_cast
-
您的代码有未定义的行为。一个合适的方法是编写用户定义的转换运算符或赋值运算符。
标签: c++