您的位置:首页 > 编程语言 > C语言/C++

C/C++学习笔记4 结构体联合体枚举

2017-11-07 16:08 393 查看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
/* 图形绘制隐形的架构
很多种类型的图元,我要绘制它们。
*/
// 图元的类型
enum SHAPE_TYPE {

SHAPE_TRIANGLE
= 0,
SHAPE_RECT
= 1,
SHAPE_CIRCLE
= 2,
SHAPE_NUM

};
 
struct point {

float x;
float y;

};
 
struct shape {
//
int type;

enum SHAPE_TYPE type;

 

union {

struct {

struct point t0;
struct point t1;
struct point t2;

}triangle;

 

struct {

float x;
float y;
float w;
float h;

}rect;

 

struct {

float c_x;
float c_y;
float r;

}circle;

}u;

};
 
void init_circle_shape(struct shape*
s,
float c_x,
float c_y,
float r)
{

s->type
= SHAPE_CIRCLE;
s->u.circle.c_x
= c_x;
s->u.circle.c_y
= c_y;
s->u.circle.r
= r;

}
 
void init_rect_shape(struct shape*
s,
float x,
float y,
float w,
float h)
{

s->type
= SHAPE_RECT;
s->u.rect.x
= x;
s->u.rect.y
= y;
s->u.rect.w
= w;
s->u.rect.h
= h;

}
 
void draw_shapes(struct shape*
shapes,
int count)
{

int i;
for (i
= 0; i < count; i++) {

switch (shapes[i].type)
{

case SHAPE_CIRCLE:{
  printf("circle
%f, %f, %f\n",
  shapes[i].u.circle.c_x,
shapes[i].u.circle.c_y,
  shapes[i].u.circle.r);
}
break;
case SHAPE_TRIANGLE:
{
 printf("triangle
%f, %f, %f, %f, %f, %f\n",
 shapes[i].u.triangle.t0.x,
shapes[i].u.triangle.t0.y,
 shapes[i].u.triangle.t1.x,
shapes[i].u.triangle.t1.y,
 shapes[i].u.triangle.t2.x,
shapes[i].u.triangle.t2.y);
}
break;
case SHAPE_RECT:
{
 printf("rect
%f, %f, %f, %f\n",
 shapes[i].u.rect.x,
shapes[i].u.rect.y,
shapes[i].u.rect.w,
shapes[i].u.rect.h);
}
break;
default:
{
 printf("Warning
Not a valid shape !!!!\n");
}
break;

}

}

}
 
void init_triangle_shape(struct shape*
s,
float x0,
float y0,
float x1,
float y1,
float x2,
float y2)
{

s->type
= SHAPE_TRIANGLE;
s->u.triangle.t0.x
= x0;
s->u.triangle.t0.y
= y0;
 
s->u.triangle.t1.x
= x1;
s->u.triangle.t1.y
= y1;
 
s->u.triangle.t2.x
= x2;
s->u.triangle.t2.y
= y2;

}
 
int main(int argc,
char**
argv) {

struct shape shapes_set[3];
 
init_triangle_shape(&shapes_set[0],
100, 100, 200, 200, 300, 300);
init_rect_shape(&shapes_set[1],
100, 100, 200, 200);
init_circle_shape(&shapes_set[2],
100, 100, 200);
 
draw_shapes(shapes_set,
3);
 
system("pause");
return 0;

}

上面案例就是使用结构体 。联合体 ,枚举的一个综合案例,可以使用一个结构体 就能做3个功能,

struct person{
       char name[64];
       int age;
       int sex;
};

struct person p;   //这样声明可以通过 p.name,p.age,p.sex来访问和赋值
struct person* p;   //声明指针类型的,可以通过p->name,p->age,p->sex来访问和赋值

枚举:
如果没有指定枚举值 ,默认第一个从0开始 ,下一个是上一个加1

enum WEAPON_TYPE{
      JIN_TYPE,
      MU_TYPE,
      SHUI_TYPE=100,
      HUO_TYPE,
      TU_TYPE,
};

JIN_TYPE = 0
MU_TYPE = 1
SHUI_TYPE=100   //指定了值
HUO_TYPE = 101
TU_TYPE = 102
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: