c/c++学习笔记(10)

结构基本知识

  结构是一个或者多个变量的集合,这些变量可以为不同的类型。ANSI标准在结构方面最主要的变化是定义了结构的赋值操作:拷贝、赋值、传递给函数、函数返回结构类型的值。

  结构声明如下:

View Code
1 struct point
2 {
3     int x;
4     int y;
5 };

  结构也可以跟其他的基本类型声明一样,如:

View Code
1 struct {...} x, y, z;

  我们可以使用以下的方式进行结构的初始化,如:

View Code
1 struct point minPoint = {0, 0};
2 //或者
3 struct point minPoint;
4 minPoint.x = 0;
5 minPoint.y = 0;

  另外,结构也是可以嵌套的,如:

View Code
1 struct rect
2 {
3     struct point minPoint;
4     struct point maxPoint;
5 };

结构与函数

  在函数中使用结构主要包括3种方式:1、传递结构的成员;2、传递整个结构;3、传递结构的指针。与C#类似,参数名和结构名相同是不会引起冲突的。代码如下:

View Code
 1 struct point{
 2     int x;
 3     int y;
 4 } pt = {0, 0};
 5 //方式1
 6 void fn(int x, int y)
 7 {
 8     //coding
 9 }
10 
11 fn(pt.x, pt.y);
12 
13 //方式2
14 void fn(struct point point)
15 {
16     //coding
17 }
18 
19 fn(pt);
20 
21 //方式3
22 void fn(struct point *point)
23 {
24     //coding
25 }
26 
27 fn(&pt);

  对于使用结构指针的时候,可以使用如下方式调用结构成员,如:

View Code
1 void fn(struct point *pt)
2 {
3     //方式1:
4     (*pt).x = 10;//括号是必须要的因为.的优先级比*高
5     (*pt).y = 20;
6     //方式2:
7     pt -> x = 10;
8     pt -> y = 20;
9 }

结构数组

  根据普通的数组差不多,暂时还没发现要点,呵呵.

  今天的学习就到这里,明天继续,加油!

posted @ 2012-06-04 07:03  ahl5esoft  阅读(161)  评论(0编辑  收藏  举报