본문 바로가기

Language/C++

[C++] 구조체 정의 - 컴도리돌이

728x90

 


Structure variable

 

<구조체 정의-예시>

struct book{
	char title[50];
    char autor[50];
    char subject[100];
    int book_id;
};


<변수 정의 - 예시>

struct book book1;

 

book은 구조체의 type 이름이며, book1은 book 구조체 타입을 가지는 변수이다.

 

book1.book_id = 0;

 

book의 구조체 타입을 가진 book1의 member에 접근하고 싶을 때 member access operation "."을 붙여서 member name을 선택한다.

 

typedef

 

typedef unsigned int MyType;

 

typedef을 사용함으로써 새로운 이름을 가진 타입을 줄 수 있다.


typedef and struct

 

struct point
{
	int xpos;
    	int ypos;
};    //a structure

struct point pos1;   // a variable of the type struct point
 
typedef struct point Point;  //give a new name Point to the type "struct point"

Point pos1; //easier to define a variable of that type

 

point라는 구조체를 선언하여 , point 구조체 형태를 가진 pos1라는 변수를 생성했다.

 

typedef을 사용하여 point의 구조체에 새로운 이름 Point라고 선언해 주었다.

 

struct point
{
	int xpos;
    	int ypos;
};

typedef struct point Point;

typedef struct point
{
	int xpos;
    	int ypos;
}Point;

typedef struct
{
	int xpos;
    	int ypos;
}Point;

initialize structure variables

 

struct point
{
	int xpos;
    	int ypos;
};

typedef struct point Point;


Point p1;
p1.xpos = 10;
p1.ypos = 20;

//or

Point p1 = {10,20};