C++学生类静态变量id输出重复值问题求助
C++静态变量ID自增失效问题解决
问题重现
我用C++编写了一个student类,声明了静态变量id,计划通过静态函数st_id()对其进行自增操作,但实际输出时该变量每次都显示相同的值。原代码如下:
#include <iostream> #include <string> using namespace std; class student { public: string name; static int id; char sec; student() { sec = 'A'; } static int st_id() { id++; return id; } void st_name() { cout << "Enter student name:"; cin >> name; } }; int student ::id = 0; int main() { int num, i; cout << "Enter the no. of students in class :"; cin >> num; student *p = new student[num]; for (i = 0; i < num; i++) { p[i].st_name(); } cout << endl << " NAME ID SEC" << endl; for (i = 0; i < num; i++) { cout << i + 1 << ")" << " " << p[i].name << " " << p[i].st_id << " " << p[i].sec << endl; } }
错误分析
- 函数地址误用:输出循环中写的
p[i].st_id是直接获取静态函数的内存地址,而非调用函数执行自增逻辑。因此所有输出的都是同一个地址值,看起来完全相同。 - 逻辑设计缺陷:即便调用
st_id(),在输出阶段才触发自增也不符合需求——每个学生应该在创建时就分配唯一ID,而非输出时才生成,否则多次输出会导致ID持续变化。
修正方案
调整类结构,给每个学生添加专属的实例ID,用静态变量维护全局计数,在构造对象时完成ID分配:
#include <iostream> #include <string> using namespace std; class student { public: string name; static int global_id; // 全局静态计数器,生成唯一ID序列 int id; // 每个学生的专属ID char sec; student() { sec = 'A'; id = st_id(); // 创建对象时分配唯一ID } static int st_id() { global_id++; return global_id; } void st_name() { cout << "Enter student name:"; cin >> name; } }; int student::global_id = 0; // 初始化全局静态计数器 int main() { int num, i; cout << "Enter the no. of students in class :"; cin >> num; student *p = new student[num]; for (i = 0; i < num; i++) { p[i].st_name(); } cout << endl << " NAME ID SEC" << endl; for (i = 0; i < num; i++) { cout << i + 1 << ")" << " " << p[i].name << " " << p[i].id << " " << p[i].sec << endl; } delete[] p; // 释放动态分配的数组内存,避免泄漏 return 0; }
修正说明
- 新增实例成员
id,存储每个学生的唯一编号,避免静态变量共享导致的逻辑混乱 - 静态变量重命名为
global_id,仅负责维护全局计数,构造函数调用st_id()完成ID分配,确保每个学生创建时就获得唯一ID - 输出时直接访问
p[i].id,保证ID值稳定唯一 - 补充
delete[] p,修复原代码的内存泄漏问题
内容的提问来源于stack exchange,提问作者Geetika
相关产品推荐
相关产品推荐

