是否可以永久地重铸 a 变量,或者有一个包装函数使变量的行为像另一种类型?
我想实现我在另一个问题中发布的内容: Typecasting variable with another typedef
更新:添加了 GCC 作为编译器。可能有一个有用的扩展?
最佳答案
是的,您可以将变量从一种类型转换为另一种类型:
int x = 5;
double y = (double) x; // <== this is what a cast looks like
但是,您不能就地修改标识符“x”的类型,如果这是您所要求的。不过,接近于此,您可以引入另一个作用域,该作用域使用某种新类型重新声明该标识符:
int x = 5;
double y = (double) x;
{
double x = y; // NOTE: this isn't the same as the 'x' identifier above
// ...
}
// NOTE: the symbol 'x' reverts to its previous meaning here.
你可以做的另一件事是:
int x = 5;
double new_version_of_x = (double) x; // Let's make 'x' mean this
#define x new_version_of_x
// The line above is pure evil, don't actually do it, but yes,
// all lines after this one will think 'x' has type double instead
// of int, because the text 'x' has been rewritten to refer to
// 'new_version_of_x'. This will likely lead to all sorts of havoc
关于c - 重新类型转换一个变量,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6619580/