静态数据成员是使用static关键字声明的类成员。即使有许多类对象,类中也只有一个静态数据成员的副本。这是因为所有对象都共享静态数据成员。创建第一个类对象时,静态数据成员始终初始化为零。
静态数据成员的语法如下:
static data_type data_member_name;
在以上语法中,使用static关键字。data_type是C ++数据类型,例如int,float等。data_member_name是提供给数据成员的名称。
演示C ++中静态数据成员的程序如下所示-
#include <iostream> #include<string.h> using namespace std; class Student { private: int rollNo; char name[10]; int marks; public: static int objectCount; Student() { objectCount++; } void getdata() { cout << "Enter roll number: "<<endl; cin >> rollNo; cout << "Enter name: "<<endl; cin >> name; cout << "Enter marks: "<<endl; cin >> marks; } void putdata() { cout<<"Roll Number = "<< rollNo <<endl; cout<<"Name = "<< name <<endl; cout<<"Marks = "<< marks <<endl; cout<<endl; } }; int Student::objectCount = 0; int main(void) { Student s1; s1.getdata(); s1.putdata(); Student s2; s2.getdata(); s2.putdata(); Student s3; s3.getdata(); s3.putdata(); cout << "Total objects created = " << Student::objectCount << endl; return 0; }
输出结果
上面程序的输出如下-
Enter roll number: 1 Enter name: Mark Enter marks: 78 Roll Number = 1 Name = Mark Marks = 78 Enter roll number: 2 Enter name: Nancy Enter marks: 55 Roll Number = 2 Name = Nancy Marks = 55 Enter roll number: 3 Enter name: Susan Enter marks: 90 Roll Number = 3 Name = Susan Marks = 90 Total objects created = 3
在上述程序中,类学生有三个数据成员,分别表示学生的卷号,姓名和分数。objectCount数据成员是一个静态数据成员,其中包含创建的Student类的对象数。Student()
是一个构造函数,它在每次创建新的类对象时都会增加objectCount。
类上有2个成员函数。该功能getdata()
从用户获取数据并putdata()
显示数据。为此的代码片段如下-
class Student { private: int rollNo; char name[10]; int marks; public: static int objectCount; Student() { objectCount++; } void getdata() { cout << "Enter roll number: "<<endl; cin >> rollNo; cout << "Enter name: "<<endl; cin >> name; cout << "Enter marks: "<<endl; cin >> marks; } void putdata() { cout<<"Roll Number = "<< rollNo <<endl; cout<<"Name = "<< name <<endl; cout<<"Marks = "<< marks <<endl; cout<<endl; } };
在该函数中main()
,有Student类的三个对象,即s1,s2和s3。对于每个对象getdata()
和putdata()
被调用。最后,显示objectCount的值。这在下面给出-
int main(void) { Student s1; s1.getdata(); s1.putdata(); Student s2; s2.getdata(); s2.putdata(); Student s3; s3.getdata(); s3.putdata(); cout << "Total objects created = " << Student::objectCount << endl; return 0; }