구조체란?
연관있는 데이터를 묶을 수 있는 문법적 장치이다.
예를 들면 학생에 관련된 데이터로 학생 이름, 학번, 휴대폰번호, 주소가 있다고 하자.
각각의 데이터들은 별도의 변수로 정의할 수 있지만 학생이라는 이름으로 묶어서 정의하면 프로그래밍이 한결 수월해질 것이다.
아래는 간단히 포인트를 예로한 구조체의 사용법이다.
구조체 선언
구조체는 struct라는 키워드를 사용해 선언한다.
struct Point { int xpos; int ypos; };
구조체 변수와 초기화
구조체를 사용하려면 Point타입의 변수를 선언하면 된다.
선언한 변수로 각 멤버에 멤버 선택 연산자(.)로 접근하여 초기화할 수 있다.
(초기화하지 않으면 쓰레기값이 들어간다.)
#include <iostream> using namespace std; struct Point { int xpos; int ypos; }; int main() { Point p; p.xpos = 5; p.ypos = 10; cout << p.xpos << endl; // 5 cout << p.ypos << endl; // 10 return 0; }
초기화 목록을 사용하여 초기화도 가능하다.
#include <iostream> using namespace std; struct Point { int xpos; int ypos; }; int main() { Point p = { 5, 10 }; cout << p.xpos << endl; // 5 cout << p.ypos << endl; // 10 return 0; }
C++11이전까지는 구조체를 작성할 때 초기화하면 오류가 발생했지만, C++11 이후로는 구조체를 작성할 때 초기화가 가능하다.
#include <iostream> using namespace std; struct Point { int xpos = 5; int ypos = 10; }; int main() { Point p; cout << p.xpos << endl; // 5 cout << p.ypos << endl; // 10 return 0; }
또한 유니폼 초기화를 사용하여 초기화할 수도 있다.
#include <iostream> using namespace std; struct Point { int xpos; int ypos; }; int main() { Point p { 5, 10 }; cout << p.xpos << endl; // 5 cout << p.ypos << endl; // 10 return 0; }
구조체 안에 함수 정의
C++에서는 구조체 안에 함수를 정의하는 것이 가능하다.
(구조체 안에 함수를 정의하게 되면 inline함수로 정의된다.)
#include <iostream> using n using namespace std; struct Point { int xpos; int ypos; void MovePosition(int x, int y) { xpos += x; ypos += y; } void AddPoint(const Point &pos) { xpos += pos.xpos; ypos += pos.ypos; } void ShowPosition() { cout << "Point [" << xpos << ", " << ypos << "]"<< endl; } }; int main() { Point p1 = { 5, 10 }; Point p2 = { 20, 30 }; p1.MovePosition(1, 2); p1.ShowPosition(); p1.AddPoint(p2); p1.ShowPosition(); return 0; }
결과
구조체 안에 너무 많이 함수를 정의하면 가독성이 떨어질 수 있다.
따라서 함수의 수가 많거나 길이가 길다면 원형 선언만 구조체 안에 두고, 외부에서 정의하는 것이 좋다.
(구조체 외부에 함수를 정의하게 되면 inline함수의 의미가 사라져, inline의 의미를 그대로 유지하려면 인라인 처리를 명시적으로 지시해야 한다.)
#include <iostream> using namespace std; struct Point { int xpos; int ypos; void MovePosition(int x, int y); void AddPoint(const Point &pos); void ShowPosition(); }; void Point::MovePosition(int x, int y) { xpos += x; ypos += y; } void Point::AddPoint(const Point &pos) { xpos += pos.xpos; ypos += pos.ypos; } void Point::ShowPosition() { cout << "Point [" << xpos << ", " << ypos << "]" << endl; } int main() { Point p1 = { 5, 10 }; Point p2 = { 20, 30 }; p1.MovePosition(1, 2); p1.ShowPosition(); p1.AddPoint(p2); p1.ShowPosition(); return 0; }
'C++' 카테고리의 다른 글
[C++] 객체지향 프로그래밍 (0) | 2019.03.13 |
---|---|
[C++] 클래스 (0) | 2019.03.08 |
[C++] new & delete (0) | 2019.03.08 |
[C++] 참조자(Reference)와 함수 (0) | 2019.03.05 |
[C++] 참조자(Reference) (0) | 2019.03.05 |