考虑以下程序:
struct A{};
int main()
{
A a;
A b = a;
A c = reinterpret_cast<A>(a);
}
编译器 (g++14) 抛出有关从类型“A”到类型“A”的无效转换的错误
。
为什么转换为相同类型无效?
最佳答案
这是不允许的,因为标准是这么说的。
您可以使用reinterpret_cast
执行一组相当有限的允许转换。参见例如cppreference 。例如,列出的第一点是:
1) An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11)
但是,将自定义类型(无指针!)强制转换为自身并不在列表中。无论如何你为什么要这么做?
关于c++ - reinterpret_cast 为相同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58429179/