nakka soft world !

정적 멤버 데이터 (static member data) 본문

프로그래밍언어/C++

정적 멤버 데이터 (static member data)

nakka 2017. 3. 17. 13:22
728x90

정적 멤버 데이터 (static member data)


class Car

{

private:

int color;

public:

int cnt = 0;

Car() { ++cnt; }

~Car() { --cnt; }

};


int main()

{

Car c1, c2;


cout << c1.cnt <<endl; // 1, cnt가 2가 되길기대했으나, 원하는 대로 되지 않음

}



전역 변수

int cnt = 0; // 전역변수

class Car

{

private:

int color;

public:

// int cnt = 0;

Car() { ++cnt; }

~Car() { --cnt; }

};


int main()

{

Car c1, c2;


cout << cnt <<endl; // 2

}



Static 멤버 Data

class Car

{

private:

int color;  // 객체당 한개씩 메모리 생성

public:

static int cnt;  // 모든 객체가 공유하는 멤버.

Car() { ++cnt; }

~Car() { --cnt; }

};

int Car::cnt = 0;  // 초기화는 여기서


int main()

{

Car c1, c2;

cout << c1.cnt <<endl; // 2

}






class Car

{

private:

int color;  // 객체당 한개씩 메모리 생성

int year;

public:

static int cnt = 0;  // error


static int cnt;

Car() { ++cnt; }

~Car() { --cnt; }

};

int Car::cnt = 0;


int main()

{

// 객체가 없어도 static멤버 변수는 메모리 생성됨.


// 클래스이름::멤버이름으로 접근

cout << Car:cnt << endl;


Car c1, c2;


cout << c1.cnt << endl; // 2

cout << sizeof(Car) << endl; // 8


// 정적 멤버 데이터에 접근하는 2가지 방법

// 1.클래스 이름으로 접금

cout << Car::cnt << endl;


// 2. 객체 이름으로 접근

cout << c1.cnt << endl;

}



정적 멤버 함구 (static member function)


class Car

{

private:

int color = 0;

int year;


static int cnt; // private으로 이동

public:

Car() { ++cnt; }

~Car() { --cnt; }


static int getCount() {return cnt;} // 정적 멤버 함수.

// 객체 없이 호출 가능.

};

int Car::cnt = 0;


int main()

{

// 몇개의 Car가 있는지 알고 싶다.

Car c1, c2;

cout << c1.getCount() << endl; // static이 아니면 객체를 만든 뒤 함수를 호출해야함


cout << Car::getCount() << endl; // static이면 객체를 만들지 않고 호출 가능 

}



// 정적 멤버 함수에서는 정적 멤버만 접근 할 수 있다.

class Test

{

private:

int data;

static int cnt;

public:

void setData(int n) { data = n; }


static int foo()

{

data = 10; // error

cnt = 10;

setData(10);

}

};

int Test::cnt = 0;


int main()

{

Test::foo();

}



// Code 배치

// Car.h

class Car

{

private:

int color;

int year;

static int cnt;

public:

Car();

~Car();

static int getCount();

};


// Car.cpp

int Car::cnt = 0;


Car::Car() { ++cnt; }

Car::~Car() { --cnt; }


/*static*/ int Car::getCount() // 핵심. 구현에는 static표시 하지 않는다.

{

return cnt;

}


int main()

{

cout << Car::getCount() << endl;

}



728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

this  (0) 2017.03.19
상수 멤버 함수 (const member function)  (0) 2017.03.19
Object Copy  (0) 2017.03.17
복사 생성자 (Copy Constructor)  (0) 2017.03.17
initialize list, 초기화 리스트  (0) 2017.03.17
Comments