【发布时间】:2015-01-25 00:09:45
【问题描述】:
就像这个例子一样(在 C 中):
typedef int type;
int main()
{
char type;
printf("sizeof(type) == %zu\n", sizeof(type)); // Outputs 1
}
输出总是局部变量type的大小。
当 C++ 不再需要在每次使用结构之前编写 struct 时,它仍然保留了 struct {type} 语法并引入了别名 (class {type}) 来显式引用结构或类。
示例(在 C++ 中):
struct type {
int m;
};
int main()
{
char type;
printf("sizeof(type) == %u\n", sizeof(type)); // Outputs 1
printf("sizeof(struct type) == %u\n", sizeof(struct type)); // Outputs 4
printf("sizeof(class type) == %u\n", sizeof(class type)); // Outputs 4
}
我的问题是,是否有办法在 C 或 C++ 中明确引用 typedef。可能是sizeof(typedef type) 之类的东西(但这不起作用)。
我知道对变量和类型使用不同的命名约定来避免这种情况是一种常见的做法,但我仍然想知道在语言中是否有办法做到这一点,或者是否没有。 :)
【问题讨论】:
-
您的文件范围 typedef 和您的块范围
char对象具有相同的名称。解决方法是重命名其中一个,以便您可以明确地引用它们。 (无论如何,type是一个糟糕的类型名称,除非它实际上代表一种类型,例如在实现编译器或解释器的代码中。) -
由于这一行,这将无法完全编译:char type;变成char int;这将引发别名或屏蔽警告。在任何情况下,printf 将始终使用局部变量 'type'
标签: c++ c typedef sizeof type-alias