如何使用联合来避免类型转换
How unions are used to avoid type coversion
我正在阅读 Bjarne Stroustrup 的 The C++ Programming Language。它在工会上声明:
“偶尔会故意使用联合来避免类型转换。例如,一个人可能,
使用 Fudge 找到指针 0 的表示:
union Fudge{
int i;
int* p;
};
int main()
{
Fudge foo;
foo.p= 0;
cout<< "the integer value of the pointer 0 is" << foo.i<< ´\n´;
} "
我知道这个代码片段给出了指针 0 的表示。但是它如何避免文中提到的类型转换?
它被称为 type punning,明确允许在 C 中使用联合,但在 C++ 中不允许。
它有效(在 C 中),因为联合的所有成员都占用相同的内存,所以实际上没有转换。您只是以不同的方式解释内存位。
我正在阅读 Bjarne Stroustrup 的 The C++ Programming Language。它在工会上声明:
“偶尔会故意使用联合来避免类型转换。例如,一个人可能, 使用 Fudge 找到指针 0 的表示:
union Fudge{
int i;
int* p;
};
int main()
{
Fudge foo;
foo.p= 0;
cout<< "the integer value of the pointer 0 is" << foo.i<< ´\n´;
} "
我知道这个代码片段给出了指针 0 的表示。但是它如何避免文中提到的类型转换?
它被称为 type punning,明确允许在 C 中使用联合,但在 C++ 中不允许。
它有效(在 C 中),因为联合的所有成员都占用相同的内存,所以实际上没有转换。您只是以不同的方式解释内存位。