如何将typedef'd结构与实例创建结合起来?

时间:2015-01-13 21:19:02

标签: c struct typedef

因此,您可以将c1c2创建为struct Complex的实例:

struct Complex {
    int real;
    int imag;
} c1, c2;

你可以这样做来输入匿名结构:

typedef struct { ... } Complex;

但有没有办法同时做两件事?

4 个答案:

答案 0 :(得分:2)

不,你不能。 typedef的语法是

typedef T type_ident;  // T is type specified by the declaration specifiers  

这意味着typedef T之后的任何内容都是类型名称,而不是该类型的实例。所以,在

typedef struct { ... } Complex, c1, c2;   

Complexc1c2都是typedef名称,类型为struct { ... }

答案 1 :(得分:1)

standard(PDF)表示这是不可能的,因为typedef只是其中一种类型说明符。就像你写了char int a;一样。

答案 2 :(得分:0)

存储类说明符(typedefstaticextern等)始终适用于整个声明。与一个声明不能声明静态和非静态变量的方式相同,typedef声明只能定义类型定义:

static int foo, bar; // Both foo and bar are static
typedef int c1, c2; // Both c1 and c2 are typedefs

答案 3 :(得分:0)

第一个表单声明了一个结构标记;第二个声明了一个typedef。主要的区别在于,如果用户不必知道它是一个结构,并且在声明它的实例时不使用关键字struct,那么第二个声明是稍微抽象的类型...&另一方面,必须定义用标签声明的结构。因此,不可能将c1和c2创建为struct Complex的实例....