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์— ๊ด€๋ จ์—†์ด ์ƒ์„ฑ๋œ ๊ฐ์ฒด์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋ฐ˜ํ™˜๋˜๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.