static

headkio·2020년 9월 9일
0

C++

목록 보기
9/35
post-thumbnail

static ?

Scope의 제한을 받는 전역 변수이다.

다른 파일에서는 수정할 수 없다.

Scope

In File, Namespace, Class, Function

static as a function member

// Cat.h
class Cat
{
	public:
    	Cat();
   	private:
    	static int mCount;
}

// Cat.cpp
int Cat::mCount = 0; // 초기화 해야한다.
Cat::Cat()
{
	mCount++;
}
  • 클래스당 하나의 메모리 공간에만 존재한다.
    각 개체마다 생기는 것이 아니다.
  • 컴파일 순간에 메모리에 할당돼 있다.

static in a function

void func(int num)
{
	static int result;
    return result += num;
}

int main() 
{
	func(1); // 1
	func(2); // 3
    
    std::cout << result; // error !
}
  • static 변수가 다음 함수 콜에서도 값이 전역 변수 처럼 유지된다.
    전역 변수처럼 유지되지만 scope를 벗어난 곳에선 사용할 수 없다.

static as a function

// header
class Math
{
	public:
		static int Square(int x);
}

// cpp
int main()
{
	std::cout << Math::Square(10); // 바로 사용 가능
}

extern ?

다른 파일의 전역 변수에 접근 가능하도록 한다.

// A.h
extern int x;

// B.c
#include "A.h"

int main() 
{
}
  • include의 동작? 컴파일시 코드를 복붙하여 파일을 만든다.

Best

  1. 함수 안에서 사용하지 말자. -> 클래스 안에서 쓸 것 (가독성)
  2. 전역 변수 대신 정적 멤버 변수를 사용하자. (Scope 제한)
profile
돌아서서 잊지말고, 잘 적어 놓자

0개의 댓글