기초 공부/C++
C++ 복습(3) typedefs 와 arithmetic operators
nsean
2023. 12. 15. 23:44
typedefs는 다른 데이터 유형의 추가 이름을 만드는 데 사용되는 키워드이다. 가독성을 높이고 오타를 줄이는 것이 주 목적이다.
예를 들어, 다음과 같은 코드가 있다고 하자.
#include <iostream>
#include <vector>
int main(){
std::vector<std::pair<std::string, int>> pairlist;
return 0;
}
이러한 복잡한 자료형은 보는 사람도, 쓰는 사람도 머리를 아프게 한다.
이를 해결하기 위해 typedef를 다음과 같이 사용 가능하다.
#include <iostream>
#include <vector>
typedef std::vector<std::pair<std::string, int>> pairlist_t;
int main(){
pairlist_t pairlist;
return 0;
}
즉, 자료형의 묶음에 대하여 새로운 닉네임을 부여한다고 생각하면 될 것이다.
이는 using을 사용하여 같은 효과를 낼 수 있다.
#include <iostream>
#include <vector>
using pairlist_t = std::vector<std::pair<std::string, int>>;
int main(){
pairlist_t pairlist;
return 0;
}
탬플릿들을 대부분 using을 사용하고 있기에 typedef보단 using 함수를 사용하는 것을 권장한다고 한다.
arithmetic operators
산술 연산자라 불리는 이것은 변수들의 간단 사칙연산들을 간결하게 표현하기 위해 사용할 수 있다.
예를 들어
int students = 20;
students = students + 1;
students += 1;
students++;
는 전부 다 같은 표현이다.
++와 --는 +1, -1에만 대응되는 표현이며, 나머지 += 표현은 모든 사칙연산 (+=, -=, /=, *=)에 사용이 가능하다.