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

C++에서 정적 클래스를 만드는 방법은 무엇입니까?


C++에는 정적 클래스와 같은 것이 없습니다. 가장 가까운 근사값은 정적 데이터 멤버와 정적 메서드만 포함하는 클래스입니다.

클래스의 정적 데이터 멤버는 클래스의 개체 수에 관계없이 메모리에 복사본이 하나만 있기 때문에 모든 클래스 개체에서 공유됩니다. 클래스의 정적 메서드는 정적 데이터 멤버, 기타 정적 메서드 또는 클래스 외부의 메서드에만 액세스할 수 있습니다.

C++에서 클래스의 정적 데이터 멤버와 정적 메서드를 보여주는 프로그램은 다음과 같습니다.

예시

#include <iostream>
using namespace std;
class Example {
   public :
   static int a;
   static int func(int b) {
      cout << "Static member function called";
      cout << "\nThe value of b is: " << b;
   }
};
int Example::a=28;
int main() {
   Example obj;
   Example::func(8);
   cout << "\nThe value of the static data member a is: " << obj.a;
   return 0;
}

출력

위 프로그램의 출력은 다음과 같습니다.

Static member function called
The value of b is: 8
The value of the static data member a is: 28

이제 위의 프로그램을 이해합시다.

클래스 예제에서 a는 데이터 유형 int의 정적 데이터 멤버입니다. func() 메서드는 "정적 멤버 함수 호출"을 출력하고 b 값을 표시하는 정적 메서드입니다. 이를 보여주는 코드 스니펫은 다음과 같습니다.

class Example {
   public :
   static int a;
   static int func(int b) {
      cout << "Static member function called";
      cout << "\nThe value of b is: " << b;
   }
};
int Example::a = 28;

main() 함수에서 객체 obj는 Example 클래스로 생성됩니다. func() 함수는 클래스 이름과 범위 확인 연산자를 사용하여 호출됩니다. 그러면 의 값이 표시됩니다. 이를 보여주는 코드 스니펫은 다음과 같습니다.

int main() {
   Example obj;
   Example::func(8);
   cout << "\nThe value of the static data member a is: " << obj.a;
   return 0;
}