클래스 내에 정적(static)으로 선언된 멤버들을 말한다.
정적 멤버는 프로그램 내에서 단 한번만 선언되어 단 한개만 존재한다.
#include <iostream>
using namespace std;
class Person
{
private:
static int num = 0;
public:
Person()
{
num++;
}
static void print()
{
cout << num << endl;
}
};
int main()
{
Person p0;
Person p1;
p0.print();
p1.print();
Person p2;
p1.print();
}
결과
2
2
3
이처럼 정적변수인 num은 객체가 다름에도 불구하고 단 한개로서 존재한다.
위의 코드를 분할하면 다음과 같다.
//alpha.h
#pragma once
#include <iostream>
class Person
{
private:
static int num;
public:
Person();
static void print();
};
//alpha.cpp
#include<iostream>
#include"alpha.h"
int Person::num = 0; //정적멤버의 정의에는 static을 붙히지 않는다.
Person::Person()
{
num++;
}
void Person::print() //정적멤버의 정의에는 static을 붙히지 않는다.
{
std::cout << num << std::endl;
}
//study.cpp
#include <iostream>
#include "alpha.h"
using namespace std;
int main()
{
Person p0;
Person p1;
p0.print();
p1.print();
Person p2;
p1.print();
Person::print(); //정적 멤버함수는 객체가 아닌 클래스를 통한 접근이 가능하다.
}
결과
2
2
3
3
정적 멤버함수는 const를 붙힐 수 없다.
static void print() const; //에러!
멤버함수는 기재하지 않더라도 암묵적으로 this를 넘기는데, 정적 멤버함수는 this를 넘기지 않기때문이다. 이에 대한 내용은 여기서 확인이 가능하다. 그렇기에 static과 const는 멤버함수에 같이 사용할 수 없다. 하지만, 멤버변수에는 같이 사용할 수 있다.
정적멤버의 접근 규칙은 다음과 같다.
정적 멤버함수에서는 정적 멤버변수만 접근이 가능하다.
하지만, 일반 멤버변수는 접근이 불가능하다.
일반 멤버함수에서는 정적 멤버(변수, 함수)에 접근이 가능하다.