我觉得这可能与C语法有关,但是我是从C ++开始编程的,所以我不确定。
基本上我已经看到了:
struct tm t;
memset( &t, 0, sizeof(struct tm) );
我对这种语法有点困惑,因为通常我希望上面的代码看起来像这样:
tm t;
memset( &t, 0, sizeof(tm) );
两者之间有什么区别,为什么要使用前者呢?
更新结构
tm
我指的是在
wchar.h
,其定义如下:
struct tm {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};
- 2021-1-111 #
- 2021-1-112 #
在C语言中,结构标记名称不会在全局名称空间上形成标识符
struct not_a_global_identifier { /* ... */ };
要引用该结构,必须使用关键字
struct
(以指定名称空间)struct not_a_global_identifer object;
或使用
typedef
在全局名称空间中创建新的标识符typedef struct not_a_global_identifer { /* ... */ } global_name_space_identifier;
C中有4个命名空间,请参阅C99标准中的6.2.3:
label names
the tags of structures, unions, and enumerations
the members of structures or unions (not a single name space ... as many as structures or unions are defined)
globalname space, for all other identifiers
这是合法的C程序:-)
int main(void) { typedef struct foobar { int foobar; } foobar; foobar boo; boo.foobar = 42; if (boo.foobar) goto foobar; foobar: return 0; }
- 2021-1-113 #
使用
struct tm t;
是为了与C兼容,其中声明了一个名为"tm
"的结构 定义了一个名为"struct tm
"的类型 但没有一个名为"tm
"的人 "(与声明该类型的两个名称的C ++相反)。 - 2021-1-114 #
用户定义的类型具有其自己的标识符空间,即,当编译器解析文件时,它将每个标识符存储在其内部 相应的空间。
当您提到
tm
,C编译器(与C ++一样)将在全局标识符空间中搜索该标识符.如果C ++编译器以前没有找到符号,它将在用户定义的类型标识符空间中查找。基本上,如果您希望具有与C ++相同的行为,请添加以下行:
typedef struct tm tm;
您可以像这样结合使用struct声明和typedef:
typedef struct tm { int field } tm;
或使用匿名结构:
typedef struct { int field } tm;
相同的行为适用于
enum
和union
:typedef enum { VALUE } myEnum; typedef union { int integer; char charArray[4]; } myUnion;
- 2021-1-115 #
在您的示例中,tm可能是类型转换结构.
例如
typedef struct tm_t { int x; }tm;
然后您就可以
tm t;
相关问题
- c++:为什么不能支撑从另一个结构派生的结构?c++c++11structlistinitialization2021-01-11 02:26
- C ++中的结构构造器?c++structconstructor2021-01-10 15:55
简单的答案是
struct
存在关键字以限制对标识符tm
的查找 仅限用户定义的类类型.可能是为了与C兼容而保留的。与其他人的说法相反,没有auto-typedef这样的东西,C和C ++在管理用户定义类型的标识符方面也没有区别.唯一的区别是查找。
您可以在此处了解更多信息