FAVORITE/C++

Structure : nested structure

Syumnny 2013. 4. 18. 00:35

Structure : Application

 

 

1. Nested structure

 

뭐. 그냥 보면 가능할 거 같지 않은가. 구조체 안에 구조체.

딱 하나 주의해야 할 점은 내부에 들어가는 가장 하위의 구조체를 먼저 만들어야 한다는 것.

 

 

Student
name
ID number
Grade
Korean
Physics
Mathematics

 

라는 nest structure를 만들고 싶다면

 

Grade
Korean
Physics
Mathematics

 

Student
name
ID number
Grade

 

라는 두 개의 structure를 순서대로 (Grade가 먼저 오도록) 선언해야 한다.

 

 

struct Grade{

double korean;

double physics;

double mathematics;

};

 

struct Student{

string name;

int id;

Grade grade;

};

 

 

 

 

 

2. Structure를 다른 변수처럼 취급하기 - Function argument & Returning

 

이것도.. 음. 그냥 하면 된다.

 - parameter

 

struct Rectangle{

double length,

width,

area;

};

// structure 선언

double getArea(double, double);

 

int main(){

Rectangle box1;

box1.area = getArea(box1.length, box1.width); // 이런식으로 함수 parameter에 그냥 넣을 수 있다 -물론 type이 맞아야한다

}

 

double getArea(double l, double w){

return l*w;

}

 

 

 - return type

 

struct Rectangle{
         double width,
         length,
         area;
};

 

Rectangle getInput();

 

int main()
{
     Rectangle box;
     box = getInput();

     // ...

}

 

Rectangle getInput(){
     Rectangle r;
     cout << "Enter the length of ur box";
     cin >> r.length;
     cout << "Enter the width of ur box";
     c in >> r.width;
     r.area= r.length*r.width;

     return r;
}

 

 

위의 방식으로 struct 를 통째로 return할 수도 있다.

큰 프로그램에서는 pass by value가 아니라 pass by reference를 사용하는 편이 빠르기는 하지만 그건 다음에 다뤄야지.  글 길어진다.

 

 

 

 

3. ++

 

보통 컴파일러는 structure 내부의 인자끼리 비교하는 것은 안 된다고 말한다.

예를 들어 바로 위의 Rectangle을 그대로 가져와서

Rectangle box1, box2;

box2 = box1  // Illegal!!

box2.length = box1.length; // Legal

 

근데 기억하기로 학교에서 나온 프로젝트때문에 리눅스에서 vi작업 할 때에는 box1==box2 같은 조건문을 본 거 같으니 가능한 컴파일러가 있을지도.

(원론적으로는 불가능하다고 가르치니까 귀찮더라도 불가능하다고 알아놓아야겠다.)

 

 

 

 

reference : Pearson Intertional 6th edi, Starting out with C++ Early objects

아 Structure 끝.(아마도.)