使用C++程序中的静态成员函数计算对象数量
这里的目标是使用静态成员函数来计算正在创建的类的对象数量。
静态数据成员通常由类的所有对象共享。如果没有给出值,静态数据成员总是初始化为0。
静态成员函数只能使用该类的静态数据成员。
这里我们使用一个名为Student的类。我们将声明一个静态数据成员count,它将存储对象的数量。一个静态成员函数rollCall(void)将显示对象的数量,作为班级中学生的学号。
下面程序中使用的方法如下
我们声明一个Student类,它具有公共数据成员int rollno和静态数据成员count。
有一个构造函数调用rollcall()并将rollno初始化为count。
有一个析构函数减少count。
静态成员函数rollcall()显示对象的数量作为学生数量并递增count。
每次创建Student的对象时,构造函数都会调用rollcall(),并且count会递增。此count被赋值给该Student对象的rollno。
在main函数中,我们创建了Student类的4个对象,例如stu1、stu2、stu3、stu4,并验证count和rollno与对象数量相同。
示例
// C++ program to Count the number of objects
// using the Static member function
#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<<"Student Count:" << ++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;
}输出
如果我们运行上面的代码,它将生成以下输出:
Student Count:1 Student 1: Roll No:1 Student Count:2 Student 2: Roll No:2 Student Count:3 Student 3: Roll No:3 Student Count:4 Student 4: Roll No:4
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP