微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决重新解释强制转换为不同类型的C ++

在阅读有关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(); 
}

运行以下代码后,它将在控制台"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; 
}  

如何打印“ A类”?自从我实例化B类以来?

解决方法

您正在做的是未定义的行为。没有正确的答案。

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

具有未定义的行为,编译器可以使用无效代码自由地执行其期望的操作。您遇到的情况可能会在不同的编译器,优化级别和目标体系结构/系统之间发生变化。

,

您在代码中使用了转换reinterpret_cast

此转换仅告诉编译器考虑指向其他类型,而不管类型是什么。 reinterpret_cast是C ++中最非法的转换,它不关注目标和源数据的安排。它将值从一种类型转换为另一种类型。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。