在C ++中的变量声明中使用struct关键字

时间:2011-10-11 16:55:21

标签: c++ struct

我觉得这可能与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 */
        };

6 个答案:

答案 0 :(得分:15)

简单的答案是,struct关键字用于限制标识符tm的查找仅限于用户定义的类类型。可能需要与C兼容。

与其他人所说的相反,没有 auto-typedef 这样的东西,C和C ++在管理用户定义类型的标识符方面也不一样。唯一的区别在于查找。

您可以阅读更多here

答案 1 :(得分:11)

在C中,struct标签名称不在全局名称空间

上形成标识符
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 Standard中的6.2.3:

  • 标签名称
  • 结构,联合和枚举的标记
  • 结构或联合的成员(不是单个名称空间......定义了结构或联合的数量)
  • 全局名称空间,用于所有其他标识符

这是一个合法的C程序: - )

int main(void) {
  typedef struct foobar { int foobar; } foobar;
  foobar boo;
  boo.foobar = 42;
  if (boo.foobar) goto foobar;
foobar:
  return 0;
}

答案 2 :(得分:1)

用户定义的类型有自己的标识符空间,即当编译器解析文件时,它将每个标识符存储在相应的空间中。

当您引用tm时,C编译器(作为C ++编译器)将在全局标识符空间中搜索此标识符。然后,如果C ++编译器之前没有找到符号,则会在用户定义的类型标识符空间中进行查找。

基本上,如果您想拥有与C ++相同的行为,请添加以下行:

typedef struct tm tm;

你可以像这样结合struct declaration和typedef:

typedef struct tm { int field } tm;

或者使用匿名结构:

typedef struct { int field } tm;

同样的行为适用于enumunion

typedef enum { VALUE } myEnum;
typedef union { int integer; char charArray[4]; } myUnion;

答案 3 :(得分:1)

使用struct tm t;是为了与C兼容,其中声明名为“tm”的结构定义了名为“struct tm”但不是名为“tm”的类型(与C ++相反,其中声明了类型的两个名称)。

答案 4 :(得分:1)

在你的例子中,tm可以是一个类型结构。

e.g。

typedef struct tm_t
{
  int x; 
}tm;

然后你可以做

tm t; 

答案 5 :(得分:0)

您可以看到下面链接的引用并从中引用“在C中,您必须显式使用struct关键字来声明结构。在C ++中,一旦定义了类型,就不需要这样做了。”有关更多信息和示例,请参阅链接。

http://msdn.microsoft.com/en-us/library/64973255%28v=vs.80%29.aspx

相关问题