ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [C++] static_member.cpp
    C++/clone code 2022. 6. 30. 10:34

     

    인스턴스 변수

    1. 객체가 생성될 때 각각의 객체들은 자신만의 멤버 변수들을 가진다. -> 인스턴스 변수

    2. 인스턴스 변수들은 별도의 기억 공간을 가지고 있다.

     

    정적 멤버 변수

    static 자료형 변수 이름;

    1. 정적 변수는 모든 객체에 공통인 변수가 필요할 때 사용한다.

    2. 정적 변수의 실제 정의는 반드시 클래스 외부에서 해야한다.

    3. 정적 변수는 객체를 만들지 않고서도 접근될 수 있다.

    Car :: numberOfCars = 100;

    c2.numberOfCars = 100;

    정적 멤버 함수

    1. 인스턴스 변수 사용(X), 정적 변수와 지역 변수만 사용할 수 있다.

    2. 정적 멤버 함수에서 정적 멤버 함수를 호출하는 것은 가능하다.

    3. this 포인터를 사용할 수 없다.

     

    car.cpp 예제
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    class Car{
        int speed;
        int gear;
        string color;
        
        int id;             //자동차의 시리얼 번호
        
    public:
        //실체화된 Car 객체의 개수를 세는 정적 변수
        static int numberOfCars;
        
        Car (int s = 0, int g = 1, string c = "white") : speed(s), gear(g), color(c)
        {
            id = numberOfCars;
        }
        
        //정적 멤버 함수
        static int getNumberOfCars(){
            return numberOfCars;
        }
    
    };
    
    //정적 변수 정의 및 초기화 -> 반드시 외부에서!
    int Car::numberOfCars = 0;
    
    int main(){
        Car c1(100, 4, "blue");
        Car c2(80, 2, "grey");
        
        int n = Car::getNumberOfCars();
        cout << "지금까지 생성된 자동차 수 = " << n << endl;
        
        return 0;
    }

    실행결과

     

     

    employee.cpp 예제
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    class Employee{
        string name;
        double salary;
        
        static int count;   //정적 변수 선언
        
    public:
        //생성자
        Employee(string n = " ", double s = 0) : name(n), salary(s){
            count++;       //객체가 생성될 때마다 정적 변수 count 증가
        }
        
        //객체가 소멸될때 호출
        ~Employee(){
            count--;
        }
        
        //정적 멤버 함수 선언
        static int getCount(){
            return count;
        }
    };
    
    int Employee::count = 0;   //정적 변수 클래스 외부에서 정의
    
    int main(){
        //객체 생성
        Employee e1("김슈니", 35000);
        Employee e2("박슈니", 24000);
        Employee e3("윤슈니", 32000);
        
        int n = Employee::getCount();
        cout << "\n현재의 직원 수 = " << n << endl;
    }

    실행 결과

Designed by Tistory.