Chinaunix首页 | 论坛 | 博客
  • 博客访问: 143334
  • 博文数量: 22
  • 博客积分: 2035
  • 博客等级: 大尉
  • 技术积分: 260
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-17 14:30
个人简介

那啥,那谁,就这样吧

文章分类

全部博文(22)

文章存档

2010年(1)

2009年(21)

分类: C/C++

2009-10-17 16:41:31

There are _3_ ways of using struct.  Here are all 3 different ways in a
program, with comments. Hope this clears up confusion.

typedef struct {
int data;
int text;
} S1;
// This will define a typedef for S1, in both C and in C++

struct S2 {
int data;
int text;
};
// This will define a typedef for S2 ONLY in C++, will create error in C (but use struct S2 can solve it).

struct {
int data;
int text;
} S3;
// This will declare S3 to be a variable of type struct.
// This is VERY different from the above two.
// This does not define a type. The above two defined type S1 and S2.
// This tells compiler to allocate memory for variable S3

void main()
{
S1 mine1; // this will work, S1 is a typedef.
S2 mine2; // this will work, S2 is also a typedef.
S3 mine3; // this will NOT work, S3 is not a typedef.

S1.data = 5; // Will give error because S1 is only a typedef.
S2.data = 5; // Will also give error because S1 is only a typedef.
S3.data = 5; // This will work, because S3 is a variable.
}
// That's how they different stuff are handy.

also !!!!!!!!!!! This next bit is important for people who using linked
lists etc.

struct S6 {
S6* ptr;
};
// This works, in C++ only.

typedef struct {
S7* ptr;
} S7;
// Although you would think this does the same thing in C OR C++....
// This DOES NOT work in C nor C++ !!!
 
事实上,要依编译器的标准为准,例如,在VC++中,允许这样的定义:
typedef struct s1
{
int a;
struct s1 *p;
}s3;
这时,s3是做为一个新类型的,不是结构变量。而如果这样声明:
struct s1
{
int a;
struct s1 *p;
}s3;
s3就做为一个结构变量,而不是一个类型。
阅读(2565) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~