반응형
자료형에게 가명 붙이기 (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
구조체 멤버에 접근할땐 .연산자로 접근이 가능하다.
반응형
'C++' 카테고리의 다른 글
5-2. C++ 난수 만들기 (0) | 2024.02.05 |
---|---|
5-1. C++ switch-case, do-while (0) | 2024.02.03 |
4-2. C++ 문자열, 열거형, 열거형 클래스 (1) | 2024.02.02 |
4-1. C++ 전역변수, 정적변수, 내부연결, 외부연결 (1) | 2024.02.02 |
3-3. C++ 비트 플래그, 비트 마스크 (1) | 2024.01.30 |