在阅读有关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
两种不相关的层次结构之间的类型产生的指针/引用是非法的-因此,不能推理由此产生的任何代码。
对于未定义的行为,编译器可以使用无效代码自由执行其希望的操作。在不同的编译器,优化级别和目标体系结构/系统之间,您所遇到的可能会有所不同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句