노력과 삽질 퇴적물

구조체 & 클래스 & 공용체 & 열거형 본문

프로그래밍note/언어. C&C++ 계열

구조체 & 클래스 & 공용체 & 열거형

알 수 없는 사용자 2011. 7. 14. 00:09

구조체


//struct 태그명
struct  tag_name
{
//구조체 멤버 선언만. 구조체내 초기값 설정불가
자료형 변수명1;
자료형 변수명2;
...; 
};
tag_name 변수명; //<- 구조체형 변수명
...; 



struct  human
{
int foot;
float run_50m_speed;
char language[15];
char eyes[15];
char skin[10];
char country[50];
};

 사용예시_1: 점 연산자  사용예시_2: 화살표 연산자
//태그명 구조체형_변수명
human p1;

//태그명.멤버;

p1.foot = 260;
p1.run_50m_speed = 10.2;
strcpy(p1.language, "Korean");
strcpy(p1.eyes, "brown");
strcpy(p1.skin, "yellow"); // p1.skin = "yellow";는 에러!
strcpy(p1.country, "Korea"); 

// p1 = {260, 10.2, "Korean", "brown", "yellow", "Korea"}; 
human p2;
human *ptr_ps = &p2;

//포인터_태그명->멤버;

ptr_ps->foot = 260;
ptr_ps->run_50m_speed = 10.2;
strcpy(ptr_ps->anguage, "Korean");
strcpy(ptr_ps->eyes, "brown");
strcpy(ptr_ps->skin, "yellow");
strcpy(ptr_ps->country, "Korea");


 



* typdef로 구조체명(태그명) 재정의
 방법1. 방법2.
//struct 태그명
typedef  struct  human
{
//구조체 멤버 선언
...;
...;
}new_태그명;
//struct 태그명
struct  human
{
//구조체 멤버 선언
...;
...;
};
typedef  human  new_태그명;





클래스


구조체와의 차이점?
=> 예약어가 class, 멤버에 접근지정자 가능, 멤버에 함수 가능.
=> 구조체나 공용체는 기본적으로 public / 클래스는 private

class 클래스명
{
public:
   //자료형 클래스멤버_변수;
   //자료형 클래스멤버_함수; //인터페이스O
   ... ;

protected:
   //자료형 클래스멤버_변수;
   //자료형 클래스멤버_함수; //상속받은 클래스에 한해서 인터페이스O
   ... ;
private:
   //자료형 클래스멤버_변수;
   //자료형 클래스멤버_함수; //인터페이스X
   ... ;
};
class object_1; // 객체(or 인스턴스) 선언1.
class object_2; // 객체(or 인스턴스) 선언2.
...;

void 클래스명::클래스멤버_함수()
{
...;
...;
}





공용체(union)


union human
{
int foot;
float run_50m_speed;
char language[15];
char eyes[15];
char skin[10];
char country[50] // 맨 마지막 멤버는 세미콜론X
};
human p3;
...
...

int main
{
p3 = {250, 9.6, "Korean", "black", "yellow", "Korea"};
cout << p3.foot << endl;
cout << p3.run_50m_speed << endl;
cout << p3.language << endl;
cout << p3.eyes << endl;
cout << p3.skin << endl;
cout << p3.country << endl;
...
return 0;

=> 구조체와 별차이 없을것 같지만, 메모리 운용에서 차이가 난다. 
=> 메모리를 한번에 한 멤버가 독식(?)해서 다른 멤버의 값이 이상하게 출력된다.
=> 최종적으로 어떤 멤버의 값이 저장된 상태인가 주의!





열거형(키워드 enum)


enum 식별자명 = {멤버명_1, 멤버명_2, ...};
//열거형 멤버는 0부터 시작



 enum human = { asian, african, european, latin };
human people1 = asian;
human people2 = african;
human people3 = european;
human people4 = latin;

int main()
{
int num1 = 0
int num2 = 1;
int num3 = 2;
int num4 = 3;

//캐스트 연산으로 변수값 재선언해서 사용.
people1 =  (human)num2;
people2 =  (human)num3;
people3 =  (human)num4;
people4 =  (human)num1; 

...
...

return 0; 
}