struct和typedef struct 有什么不同呢?
来源:互联网 发布:c语言32个关键字用法 编辑:程序博客网 时间:2024/05/16 10:56
[提问] 最近在论坛中经常看到有些初学者问起, struct _x1 { ...}x1; 和 typedef struct _x2{ ...} x2; 有什么不同?
[知识点]
结构也是一种数据类型, 可以使用结构变量, 因此, 象其它
类型的变量一样, 在使用结构变量时要先对其定义。
定义结构变量的一般格式为:
struct 结构名
{
类型 变量名;
类型 变量名;
...
} 结构变量;
结构名是结构的标识符不是变量名。
另一种常用格式为:
typedef struct 结构名
{
类型 变量名;
类型 变量名;
...
} 结构别名;
另外注意: 在C中,struct不能包含函数。在C++中,对struct进行了扩展,可以包含函数。
========================================================================
实例1: struct.cpp
#include <iostream>
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<< "pt1.x=" << pt1.x << "pt.y=" <<pt1.y <<endl;
//hello pt2;
//pt2.x = 8;
//pt2.y =10;
//cout<<"pt2.x="<< pt2.x <<"pt2.y="<<pt2.y <<endl;
//上面的hello pt2;这一行编译将不能通过. 为什么?
//因为hello是被定义了的对象实例了.
//正确做法如下: 用hello.x和hello.y
hello.x = 8;
hello.y = 10;
cout<< "hello.x=" << hello.x << "hello.y=" <<hello.y <<endl;
return 0;
}
- struct和typedef struct 有什么不同呢?
- 声明 struct x1 { ...}; 和 typedef struct { ...} x2; 有什么不同?
- struct 和typedef struct什么区别
- struct 和typedef struct什么区别
- c和c++中struct有什么不同?C++中的struct和class有什么不同?
- typedef struct A{};和 typedef struct A{}A;有什么区别?
- struct和typedef struct
- struct和typedef struct
- struct和typedef struct
- struct 和 typedef struct
- struct和typedef struct
- struct和typedef struct
- struct和typedef struct
- struct和typedef struct
- struct和typedef struct
- typedef struct和struct
- struct和typedef struct
- struct和typedef struct
- 互斥对象(转)
- SMS 2003操作指南系列之二:SMS 2003软件分发指南(配置篇)
- 如何在struts+spring+hibernate的框架下构建低耦合高内聚的软件
- 转载一个SAP下载工具的代码,仅用于学习(来源于:http://www.dalestech.com/)
- Javascript 技巧大全http://www.playes.net/Blog/450.asp
- struct和typedef struct 有什么不同呢?
- SMS 2003操作指南系列之三:SMS 2003软件分发指南(实施篇)
- Expression Templates
- 正则表达式介绍
- 控件的呈现方法(Rendering)的内核
- winfrom使用多线程
- java 类型提升的约定
- 关于flash嵌入的一点东西 ----遗漏的知识点
- 在状态条中显示鼠标的设备坐标与逻辑坐标