在C++中将对象转换为不相关对象的正确方法是什么

#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和做 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;
}

但是,如果你坚持“无关”...

在 C++ 中将对象转换为不相关对象的正确方法是什么

空无一人。

reinterpret_cast是使编译器静音的好方法,但它b = *reinterpret_cast<c2*>(&a);是未定义的行为。人们通常reinterpret_cast认为它是一个神奇的任意对任意类型的演员,但事实并非如此。有关定义的案例的相当有限的列表,请参见此处。不相关类型的对象之间的转换不在列表中。

  • @Dan Yes, you are simply converting *a pointer* of type `c1*` into *a pointer* of type `c2*`. That much is well-defined. What is not defined is *accessing* a `c1` object *as-if* it were an unrelated `c2` object, which is what happens when you dereference the casted pointer and assign the result to `b`. See [what is type punning & what is the purpose of it?what happens if i use it or not use it?](https://stackoverflow.com/questions/44137442/) and [What is the strict aliasing rule](https://stackoverflow.com/questions/98650/)

以上是在C++中将对象转换为不相关对象的正确方法是什么的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>