重新解释转换为不同类型的 C++

Ama*_*man 1 c++ casting reinterpret-cast

在阅读有关 Reinterpret cast 的内容时,我正在检查以下代码。

class Type1 {
public:

    Type1() {
        a = "Class Type 1";
    }
    void get1()
    {
        std::cout << a;
    }
private:
    std::string a;
};

class Type2 {
public:
    
    Type2() {
        b = "class Type 2";
    }

    void get2()
    {
        std::cout << b;
    }
private:
    std::string b;
};

int main()
{
    
    Type1* type1 = new Type1();

    //converting Pointer
    Type2* type2 = reinterpret_cast<Type2*>(type1);

    // accessing the function of class A 
    type2->get2(); 
}
Run Code Online (Sandbox Code Playgroud)

运行以下代码后,它会在控制台中打印 "Class Type 1"

现在type1是类型的指针,Type1我将它转换为Type2并存储在type2. 现在,当我调用type2->get2(); 它是打印a实例化的数据成员Type1还是编译器正在动态更改函数?

同样在以下代码中。

#include <iostream> 
using namespace std; 
  
class A { 
public: 
    void fun_a() 
    { 
        cout << " In class A\n"; 
    } 
}; 
  
class B { 
public: 
    void fun_b() 
    { 
        cout << " In class B\n"; 
    } 
}; 
  
int main() 
{ 
    // creating object of class B 
    B* x = new B(); 
  
    // converting the pointer to object 
    // referenced of class B to class A 
    A* new_a = reinterpret_cast<A*>(x); 
  
    // accessing the function of class A 
    new_a->fun_a(); 
    return 0; 
}  
Run Code Online (Sandbox Code Playgroud)

“在 A 班”是如何打印的?因为我实例化了 B 类?

Hum*_*ler 9

你在做什么是未定义的行为。对此没有正确的答案。

在 C++ 中使用由reinterpret_cast不相关层次结构的两种类型之间产生的指针/引用是非法的——因此无法推理任何由此产生的代码。

对于未定义的行为,编译器可以自由地对无效代码做它想做的事情。您遇到的情况可能会因不同的编译器、优化级别和目标体系结构/系统而异。