小编Ama*_*man的帖子

重新解释转换为不同类型的 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(); 
}
Run Code Online (Sandbox Code Playgroud)

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

现在type1是类型的指针, …

c++ casting reinterpret-cast

1
推荐指数
1
解决办法
112
查看次数

标签 统计

c++ ×1

casting ×1

reinterpret-cast ×1