2个相似的typedef定义的差异
Differences in 2 similar typedef definition
你可以这样定义一个Point结构体:
typedef struct
{
int x, y;
} Point;
,也可以这样:
typedef struct Point
{
int x, y;
};
有什么区别?
考虑下面给出的C
代码,
typedef struct
{
int x, y;
} Point;
int main()
{
Point a;
a.x=111;
a.y=222;
printf("n%d %dn",a.x,a.y);
}
上面的代码将执行,没有任何错误或警告,而下面的C
代码将给你一个错误(error: 'Point' undeclared
)和一个警告(warning: useless storage class specifier in empty declaration
)。
typedef struct Point
{
int x, y;
};
int main()
{
Point a;
a.x=111;
a.y=222;
printf("n%d %dn",a.x,a.y);
}
要纠正这个错误,你必须声明结构变量a
,如下所示,
int main()
{
struct Point a;
a.x=111;
a.y=222;
printf("n%d %dn",a.x,a.y);
}
第二个例子,typedef
语句没有效果。编译器可能会忽略它或者给你一个警告。
与此代码的不同之处:
typedef struct Point
{
int x, y;
} Point;
允许您将Point用作类型或结构体。我认为使用结构名作为类型,甚至作为变量是一种不好的做法,但您可以这样做。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 如何重新定义MPI_FLOAT,MPI_DOUBLE以 typedef 的方式
- 使用LASlib时BOOL typedef重新定义
- "typedef"类型名称是否可以像"struct"定义那样声明指向结构的指针?
- 具有未声明/未定义类型的 typedef 结构
- typedef 应该同时在类定义和类声明中吗?
- 定义 ostream 运算符<<用于类中定义的 typedef
- 模板化类,包含由 typedef 定义的类对象的向量.如何称呼它们
- C 通过Typedef定义新类型
- Typedef已定义的功能
- typedef 中的自定义类型为 Qt MetaType
- 错误:使用不同类型的 Typedef 重定义
- 带有STD ::向量的模板Typedef具有自定义分配器
- 在Visual Studio中定义与Typedef枚举发生冲突的原因是什么?
- 如何比较/排序包含自定义 typedef 的列表容器的元素
- 如何为联合成员定义typedef
- 为函数定义 typedef,该函数返回指向类似自身的函数的函数指针
- 在本地范围内重新定义typedef
- 定义Typedef?(UDP数据包)
- 使用基类并从中重新定义typedef