Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++ 프로그램에서 정적 멤버 함수를 사용하여 개체 수 계산


여기의 목표는 정적 멤버 함수를 사용하여 생성되는 클래스의 개체 수를 계산하는 것입니다.

정적 데이터 멤버는 일반적으로 클래스의 모든 개체에서 공유됩니다. 값을 지정하지 않으면 정적 데이터 멤버는 항상 0으로 초기화됩니다.

정적 멤버 함수는 해당 클래스의 정적 데이터 멤버만 사용할 수 있습니다.

우리는 여기에 학생 클래스를 사용하고 있습니다. 객체 수를 저장할 정적 데이터 멤버 수를 선언합니다. 객체 수를 클래스의 학생 수로 표시하는 정적 멤버 함수 rollCall(void)

아래 프로그램에서 사용된 접근 방식은 다음과 같습니다.

  • 우리는 공개 데이터 멤버가 int rollno이고 정적 데이터 멤버 수가 있는 학생 클래스를 선언합니다.

  • rollcall()을 호출하고 count로 rollno를 초기화하는 생성자가 있습니다.

  • 개수를 줄이는 소멸자가 있습니다.

  • 정적 멤버 함수 rollcall()은 객체의 개수를 학생 개수로 표시하고 개수를 증가시킵니다.

  • Student 객체가 생성될 때마다 생성자는 rollcall()을 호출하고 count는 증가합니다. 이 개수는 해당 학생 개체의 롤 번호에 할당됩니다.

  • 기본적으로 Student 클래스의 4개 객체를 stu1,stu2,stu3,stu4로 생성하고 count 및 rollno가 no와 동일한지 확인했습니다. 개체 수.

// 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<< "\n"; //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