static은 link의 개념과 scope block의 개념으로 구분되는데
static - link의 개념은
간단하게 internal linkage를 의미하고
아래의 링크를 참고하면 된다
https://motivelessstudy.tistory.com/313
static - scope block의 개념은
일반적인 static과
static member variable/function로 구분된다
1) 일반적인 static
초기화가 단 한 번만 실행된다
#include <iostream>
void func()
{
static int a = 0;
std::cout << a << std::endl;// 계속 0이 출력
}
int main()
{
for (int i = 0; i < 5; i++)
{
func();
}
}
2) static member variable/function
모든 클래스가 하나의 static 변수를 공유한다
#include <iostream>
class A
{
public:
int i;
static int s;
static void func();
};
int A::s = 0;
int main()
{
A a1;
A a2;
A a3;
a1.s = 10;
std::cout << a1.s << std::endl;// 10
std::cout << a2.s << std::endl;// 10
std::cout << a3.s << std::endl;// 10
}
# static의 header와 cpp
static에 대한 선언이 header 파일에 있다는 가정하에,
static에대한 정의도 header 파일에 넣게 되면
main.cpp 파일과 해당 cpp 파일에 static에 대한 definition이 중복되며
컴파일이 진행이 된다
결국, 링크 프로세스 과정에서 충돌할 수 있기 때문에
static에 대한 정의는 반드시 cpp에 작성해줘야 한다
추가적으로, C++ 17부터는 선언과 정의를 동시에 하는 inline이라는 키워드를 활용할 수도 있다
'C++ > [노코프] Tips' 카테고리의 다른 글
[C++ Tips] Function Overloading (0) | 2024.04.08 |
---|---|
[C++ Tips] 싱글톤 (0) | 2024.04.07 |
[C++ Tips] extern vs. static (0) | 2024.04.07 |
[C++ Tips] std::string (0) | 2024.04.06 |
[C++ Tips] 상속 (0) | 2024.04.06 |