본문 바로가기
C++

4-3. C++ 자료형에게 가명 붙이기 (type aliases), 구조체 (struct)

by kwon5346 2024. 2. 2.
반응형

자료형에게 가명 붙이기 (Type aliases)

typedef 뒤에 이름을 붙여주고 싶은 자료형을 써주고 가명을 사용한다.

#include <iostream>
#include <vector>

int main()
{
   using namespace std;

   typedef vector<pair<string,int>> pairlist_t;
   // using pairlist_t = vector<pair<string,int>> 로도 사용가능

   pairlist_t pairlist1;
   pairlist_t pairlist2;

   return 0;
}

내 프로그램에서 이 자료형을 표현할때 이 가명을 쓰겠다고 선언하는 것이다.
기본적으로 긴 문장을 짧게 줄이는데 매우 편리하게 사용할 수 있다.


구조체 (struct)

다양한 요소들을 묶어서 마치 하나의 자료형인 것처럼,
하나의 사용자 정의 자료형인 것처럼 사용할 수 있게 해주는 것이 구조체이다.

#include <iostream>
#include <string>

using namespace std;

struct Person     // 4 + 4 + 8 + 24 = 40
{
   int age;       // 4  bytes
   float height;  // 4 bytes
   double weight; // 8 bytes
   string name;   // 24 bytes

   void print()
   {
      cout << "age : " << age << " height : " << height << " weight : ";
      cout << weight << " name : " << name << endl;
   }
};

struct Family
{
   Person me;
   Person mom;
   Person dad;
   Person sister;

   void printName()
   {
      cout << me.name << " " << mom.name;
      cout << " " << dad.name << " " << sister.name << endl;
   }
};

int main()
{
   Person me     { 25, 180.3, 74.5, "Jack" };
   Person mom    { 49, 160.2, 55.7, "Olivia"};
   Person dad    { 52, 175.3, 70.2, "Daniel"};
   Person sister { 27, 162.5, 52.2, "Emma"};

   me.print();
   mom.print();
   dad.print();
   sister.print();

   Family family { me, mom, dad, sister };
   family.printName();

   cout << sizeof(Person) << endl; // 40

   return 0;
}
// output
age : 25 height : 180.3 weight : 74.5 name : Jack
age : 49 height : 160.2 weight : 55.7 name : Olivia
age : 52 height : 175.3 weight : 70.2 name : Daniel
age : 27 height : 162.5 weight : 52.2 name : Emma
Jack Olivia Daniel Emma
40

구조체 멤버에 접근할땐 .연산자로 접근이 가능하다.

반응형