使用C ++程序中的静态成员函数计算对象数
此处的目标是计算使用静态成员函数创建的类的对象数。
静态数据成员通常由该类的所有对象共享。如果未给出任何值,则静态数据成员始终以0初始化。
静态成员函数只能使用该类的静态数据成员。
我们在这里使用类学生。我们将声明一个静态数据成员计数,该计数将存储对象的计数。静态成员函数rollCall(void)将显示对象的数量,作为类中学生的滚动编号。
以下程序中使用的方法如下
我们声明一个具有公共数据成员introllno和静态数据成员计数的Student类。
有一个构造函数,它rollcall()用count调用并初始化rollno。
有一个减少数量的析构函数。
静态成员函数rollcall()将对象的计数显示为学生计数,并增加计数。
每次创建Student对象时,构造函数调用rollcall()和计数都会增加。此计数分配给该Student对象的rollno。
首先,我们创建了Student类的4个对象,分别为stu1,stu2,stu3,stu4,并验证了count和rollno与no相同。对象。
示例
// C++ program to Count the number of objects
//使用静态成员函数
#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<<"学生人数:" << ++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;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
学生人数:1 Student 1: Roll No:1 学生人数:2 Student 2: Roll No:2 学生人数:3 Student 3: Roll No:3 学生人数:4 Student 4: Roll No:4