Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++ 정적 멤버 함수를 활용한 객체 수 세기 방법

이 글의 목표는 정적(static) 멤버 함수를 사용하여 클래스로부터 생성된 객체의 개수를 세는 것입니다.

정적 데이터 멤버는 해당 클래스의 모든 객체가 공유하는 멤버입니다. 별도의 초기값이 지정되지 않으면 항상 0으로 초기화됩니다. 또한 정적 멤버 함수는 그 클래스의 정적 데이터 멤버만 사용할 수 있다는 특징이 있습니다.

여기서는 Student 클래스를 예제로 사용합니다. 객체의 개수를 저장할 정적 데이터 멤버 count를 선언하고, 학생들의 출석 번호처럼 객체 수를 출력하는 정적 멤버 함수 rollCall(void)을 구현합니다.

프로그램의 동작 방식

  • public 데이터 멤버인 int rollno와 정적 데이터 멤버 count를 가진 Student 클래스를 선언합니다.
  • 생성자는 rollCall()을 호출하며, rollno를 count 값으로 초기화합니다.
  • 소멸자는 count 값을 감소시킵니다.
  • 정적 멤버 함수 rollCall()은 현재까지 생성된 객체 수를 'Student Count' 형태로 출력한 뒤 count를 증가시킵니다.
  • Student 객체가 생성될 때마다 생성자가 rollCall()을 호출하여 count가 증가하고, 이 값이 해당 객체의 rollno에 할당됩니다.

main 함수에서는 stu1, stu2, stu3, stu4라는 네 개의 Student 객체를 생성하여, count와 rollno가 실제 객체 수와 일치하는지 확인합니다.

예제 코드

// C++ program to Count the number of objects
// using the Static member function
#include <iostream>
using namespace std;
class Student {
public:
    int rollno;
    static int count;
public:
    Student(){
        rollCall();
        rollno=count;
    }
    ~Student()
    { --count; }
    static void rollCall(void){
        cout <<endl<<"Student Count:" << ++count<< "
"; //object count
    }
};
int Student::count;
int main(){
    Student stu1;
    cout<<"Student 1: Roll No:"<<stu1.rollno;
    Student stu2;
    cout<<"Student 2: Roll No:"<<stu2.rollno;
    Student stu3;
    cout<<"Student 3: Roll No:"<<stu3.rollno;
    Student stu4;
    cout<<"Student 4: Roll No:"<<stu4.rollno;
    return 0;
}

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.

Student Count:1
Student 1: Roll No:1
Student Count:2
Student 2: Roll No:2
Student Count:3
Student 3: Roll No:3
Student Count:4
Student 4: Roll No:4

출력 결과에서 확인할 수 있듯이, 객체가 생성될 때마다 정적 멤버 count가 증가하며 각 객체의 rollno에 순차적으로 할당됩니다. 이처럼 정적 멤버 변수와 정적 멤버 함수를 활용하면 클래스 단위로 공유되는 정보를 손쉽게 관리할 수 있습니다.