C++类型双关

Posted 放飞梦想C

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++类型双关相关的知识,希望对你有一定的参考价值。

Σ(っ °Д °;)っ

#include<iostream>

struct Entity
{
	int x, y;
	int* GetPtr()
	{
		return &x;
	}
	/*Entity* GetPtr()
	{
		return this;
	}*/
};

int main()
{
	Entity e = { 1,2 };
	int* ptr = (int*)&e;

	int x = *(int*)((char*)&e);
	int y = *(int*)((char*)&e + 4);

	std::cout << x << " " << y << " " << ptr[0] << " " << ptr[1] << std::endl;
	//	1 2 1 2
	ptr = e.GetPtr();
	//ptr = (int*)e.GetPtr();
	ptr[0] = 4;
	ptr[1] = 5;

	std::cout << ptr[0] << " " << ptr[1] << std::endl;
	// 4 5
	std::cin.get();
}

以上是关于C++类型双关的主要内容,如果未能解决你的问题,请参考以下文章

使用带有联合的类型双关语的问题

什么是类型双关语,它的目的是什么?

GCC 7,aligned_storage 和“取消引用类型双关指针将破坏严格别名规则”

memcpy 可以用于类型双关语吗?

是否通过 C99 中未指定的联合进行类型双关,并且它是否已在 C11 中指定?

是否通过 C99 中未指定的联合进行类型双关,并且它是否已在 C11 中指定?