微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > struct和typedef struct

struct和typedef struct

时间:11-27 来源:互联网 点击:

第四篇:C/C++中typedef struct和struct的用法

struct _x1 { ...}x1; 和 typedef struct _x2{ ...} x2; 有什么不同?

其实, 前者是定义了类_x1和_x1的对象实例x1, 后者是定义了类_x2和_x2的类别名x2 ,

所以它们在使用过程中是有取别的.请看实例1.

[知识点]

结构也是一种数据类型, 可以使用结构变量, 因此, 象其它 类型的变量一样, 在使用结构变量时要先对其定义。

定义结构变量的一般格式为:

struct 结构名

{

类型 变量名;

类型 变量名;

...

} 结构变量;

结构名是结构的标识符不是变量名。

另一种常用格式为:

typedef struct 结构名

{

类型 变量名;

类型 变量名;

...

} 结构别名;

另外注意: 在C中,struct不能包含函数。在C++中,对struct进行了扩展,可以包含函数。

======================================================================

实例1: struct.cpp

#include

using namespace std;

typedef struct _point{

int x;

int y;

}point; //定义类,给类一个别名

struct _hello{

int x,y;

} hello; //同时定义类和对象

int main()

{

point pt1;

pt1.x = 2;

pt1.y = 5;

cout< "ptpt1.x=" < pt1.x < "pt.y=" //hello pt2;

//pt2.x = 8;

//pt2.y =10;

//cout<"pt2pt2.x="< pt2.x <"pt2.y="//上面的hello pt2;这一行编译将不能通过. 为什么?

//因为hello是被定义了的对象实例了.

//正确做法如下: 用hello.x和hello.y

hello.x = 8;

hello.y = 10;

cout< "hellohello.x=" < hello.x < "hello.y=" return 0;

}

第五篇:问答

Q:用struct和typedef struct 定义一个结构体有什么区别?为什么会有两种方式呢?

struct Student
{
int a;
} stu;
typedef struct Student2
{
int a;
}stu2;

A:

事实上,这个东西是从C语言中遗留过来的,typedef可以定义新的复合类型或给现有类型起一个别名,在C语言中,如果你使用
struct xxx
{
}; 的方法,使用时就必须用 struct xxx var 来声明变量,而使用
typedef struct
{
}的方法 就可以写为 xxx var;
不过在C++中已经没有这回事了,无论你用哪一种写法都可以使用第二种方式声明变量,这个应该算是C语言的糟粕。

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top