在c++中,有什么区别:

struct Foo { ... };

and:

typedef struct { ... } Foo;

当前回答

不能对typedef结构使用前向声明。

该结构本身是匿名类型,因此没有实际的名称来转发声明。

typedef struct{
    int one;
    int two;
}myStruct;

像这样的前向声明是行不通的:

struct myStruct; //forward declaration fails

void blah(myStruct* pStruct);

//error C2371: 'myStruct' : redefinition; different basic types

其他回答

Struct是用来创建数据类型的。 typedef用于为数据类型设置昵称。

一个更重要的区别是:typedef不能前向声明。因此,对于typedef选项,你必须#include包含typedef的文件,这意味着#包含你的.h的所有内容也包括该文件,无论它是否直接需要它,等等。它肯定会影响大型项目的构建时间。

如果没有typedef,在某些情况下,你可以只添加结构Foo的前向声明;在.h文件的顶部,并且在.cpp文件中只有#include结构定义。

c++中'typedef struct'和'struct'的一个重要区别是'typedef struct'中的内联成员初始化将不起作用。

// the 'x' in this struct will NOT be initialised to zero
typedef struct { int x = 0; } Foo;

// the 'x' in this struct WILL be initialised to zero
struct Foo { int x = 0; };

在c++中没有区别,但我相信在C中,它会允许你声明结构Foo的实例,而无需显式地执行:

struct Foo bar;

不能对typedef结构使用前向声明。

该结构本身是匿名类型,因此没有实际的名称来转发声明。

typedef struct{
    int one;
    int two;
}myStruct;

像这样的前向声明是行不通的:

struct myStruct; //forward declaration fails

void blah(myStruct* pStruct);

//error C2371: 'myStruct' : redefinition; different basic types