如何在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;
      return 0;
   }
};
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

现在让我们理解上述程序。

在Example类中,a是int类型的静态数据成员。func()方法是一个静态方法,它打印“Static member function called”并显示b的值。显示此内容的代码片段如下。

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

在main()函数中,创建了一个Example类的对象obj。通过使用类名和范围解析运算符调用func()函数。然后显示a的值。显示此内容的代码片段如下。

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

更新于:2023年4月13日

23K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.