利用静态数据成员的使用,建立一个学生类(属性有姓名,学号),统计全班学生人数
时间: 2024-05-04 07:19:41 浏览: 47
以下是使用静态数据成员的学生类示例代码:
```cpp
#include <iostream>
#include <string>
class Student {
public:
Student(const std::string& name, const std::string& id) : name_(name), id_(id) {
count_++; // 每次新建一个学生对象,计数器加一
}
const std::string& GetName() const {
return name_;
}
const std::string& GetId() const {
return id_;
}
static int GetCount() { // 静态成员函数,用于获取计数器的值
return count_;
}
private:
std::string name_;
std::string id_;
static int count_; // 静态数据成员,用于统计全班学生人数
};
int Student::count_ = 0; // 静态数据成员的定义和初始化
int main() {
Student s1("Tom", "001");
Student s2("Jerry", "002");
Student s3("Kevin", "003");
std::cout << "Total number of students: " << Student::GetCount() << std::endl;
return 0;
}
```
运行结果如下:
```
Total number of students: 3
```
在这个示例中,使用了静态数据成员 `count_` 统计全班学生人数。每次新建一个学生对象时,计数器 `count_` 的值加一。同时,定义了一个静态成员函数 `GetCount()`,用于获取计数器的值。在 `main()` 函数中,创建了三个学生对象,并输出了全班学生人数。