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
现在让我们了解上面的程序。
在类Example中,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(),创建了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;
}