static Members
๋๋๋ก๋, ํด๋์ค์ ๊ฐ์ฒด๋ค์ด ๋ชจ๋ ๊ณต์ ํ๋ ๋ณ์๋ฅผ ๊ฐ์ง๋ ๊ฒ์ด ์ฉ์ดํ๋ค. ์ ์ญ๋ณ์์๋ ์กฐ๊ธ ๋ค๋ฅธ ์ ์ด ์๋ค
- ๊ณตํต์ ย : ํน์ ํจ์๋ ํด๋์ค๊ฐ ๋๋๊ณ ๋์ ๋ณ์๊ฐ ์ฌ๋ผ์ง์ง ์๋๋ค.
- ์ฐจ์ด์ ย : ํน์ ํด๋์ค์ ๊ตฌ์๋์ด ์๋ค.
์ด๊ฒ์ ๊ตฌํํ๊ณ ์ถ์ผ๋ฉดย Staticย ํค์๋๋ฅผ ๋ถ์ฌ์ฃผ๋ฉด ๋๋ค.
ํน์ดํ ์ ์, ์ด ๋ณ์๋ฅผ ์ฌ์ฉํ๊ธฐ ์ ์ ์ด๊ธฐํ๋, ํด๋์ค ๋ด๋ถ์์ ํ์ง ์๊ณ ,ย ์ ์ญ๋ณ์์ฒ๋ผ main ํจ์ ๋ฐ์์ ํ๋ค.
#include <iostream>
using namespace std;
class Point{
private:
int x;
int y;
// ์ ์ธ!!
static int numCreatedObjects;
public:
// ์ด๊ธฐํ์ ๊ฐ์๋ฅผ ํ๋์ฉ ๋๋ ค์ค
Point(): x(0), y(0){
numCreatedObjects++;
}
Point(int _x, int _y): x(_x), y(_y) {
numCreatedObjects++;
}
// public์์ ์ด ์ซ์๋ฅผ ์ ๊ทผ ํ ์ ์๊ฒ ํจ์๋ฅผ ๋ง๋ค์ด์ค.
static int getNumCreatedObject(){ return numCreatedObjects; }
};
// ์ฌ๊ธฐ์ ์ด๊ธฐํ๋ฅผ ํด์ค๋ค!
int Point::numCreatedObjects = 0;
int main(){
Point pt1(1, 2);
cout << pt1.getNumCreatedObject() << endl;
Point pt2(3, 3);
cout << pt1.getNumCreatedObject() << endl;
cout << pt2.getNumCreatedObject() << endl;
return 0;
}
1
2
2
pt1 ๊ณผ pt2์ ๊ด๋ จ์์ด ์์ฑ๋ ๊ฐ์ฒด์ ๊ฐ์๋งํผ ๋ฐํ๋๋ ๊ฒ์ ์ ์ ์๋ค.