프로그래밍 언어/C++

C++ static (정적 변수 / 함수)

ShovelingLife 2022. 9. 13. 07:21

정적 변수는 선언 후 외부에서도 선언을 한 번 더 해줘야한다.

Test.h

#pragma once

class Test
{
public:
    static int Val;
};

cpp 파일에서 재선언 해주면 된다. 그리고 접근하기 위해선 클래스::변수 또는 함수로 해주면 된다.

#include <iostream>
#include "Test.h"

using namespace std;

int Test::Val = 0;

int main()
{
    cout << Test::Val << endl;
}

const일 때만 초기값 설정이 가능하다.

#pragma once

class Test
{
public:
    const static int Val = 10;
};
#include <iostream>
#include "Test.h"

using namespace std;

const int Test::Val;

int main()
{
    cout << Test::Val << endl;
}

// 답 10

함수일 땐 더 간단하다 재 선언 해줄 필요없다.

#pragma once

class Test
{
public:
    static void Fn()
    {

    }
};

아래와 같이 변경했다.

#pragma once

class Test
{
public:
    static void Fn();
};
#include <iostream>
#include "Test.h"

using namespace std;

void Test::Fn()
{
    cout << "테스트" << endl;
}

int main()
{
    Test::Fn();
}

// 테스트