c++ - 使用重新解释指向整数的指针

标签 c++ reinterpret-cast

我正在尝试使用 reinterpret_cast 将指针转换为另一种类型

class MyClassA
{
 int x;
 int y;
 public:
    MyClassA();
    ~MyClassA();
};

class MyClassB
{
 int x;
 int y;
 public:
    MyClassB();
    ~MyClassB();
};

例如,如果我将指向 MyClassA 的指针转换为 MyClassB,那么使用 reinterpret_cast 这种转换是否有效?代码可移植性如何?

而且,正如我指出的:

(5.2.10/4) A pointer can be explicitly converted to any integral type large enough to hold it.

这是否意味着任何指针,例如 MyClassA* 只能转换为 int* 指针?如果我是正确的?

最佳答案

(5.2.10/4) A pointer can be explicitly converted to any integral type large enough to hold it.

这意味着 int*int。指针不是整数类型。

转换不相关类型的指针是个坏消息,不应该这样做。它可能 可以工作,但不可移植。

虽然继承会起作用。让类型从基类继承!

关于c++ - 使用重新解释指向整数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8459219/

相关文章:

python - 使用 SWIG 包装 C/C++ 库

c++ - reinterpret_cast - 奇怪的行为

c++ - wxWebView 中的 ObjectForScripting?

c++ - 如何将文本文件中的数据成对?

C++ 异常代码查找

c++ - 为什么这个 reinterpret_cast 不编译?

c++ - 在没有警告/错误的情况下对引用进行隐式重新解释

c++ - gmock gtest 如何设置模拟

C++ 编译器说 "inconsistent deduction for auto return type"

c++ - "cast to first member of standard layout"类型双关规则是否扩展到数组?