#include <iostream.h> #include <string.h> class CStudent { public: CStudent(char *n, int a); ~CStudent(); static void SetAge(int age); private: char *name; int age; static int nTotalObj; }; int CStudent::nTotalObj = 0; CStudent::CStudent(char *n, int a) :age(a) { int nLen = strlen(n); name = new char[nLen+1]; strcpy(name,n); name[nLen] = '\0'; nTotalObj++; } CStudent::~CStudent() { delete[] name; nTotalObj--; } void CStudent::SetAge(int age) { this->age = age; } void main() { CStudent stu1("张三",25); CStudent str2("李四",26); cout<<"CStudent::nTotalObj="<<CStudent::nTotalObj<<endl; }问题三:如果不改变主函数和类 CStudent 中的成员变量的属性,应该如何改正该程序?
时间: 2024-03-24 10:40:15 浏览: 72
vc++2008编译不了#include<iostream.h>头文件
4星 · 用户满意度95%
这个程序存在一个问题,就是在类 CStudent 中定义的 name 和 age 成员变量没有进行释放,会导致内存泄漏。解决方法是在类的析构函数中释放这些成员变量。
修改后的代码如下:
```
#include <iostream.h>
#include <string.h>
class CStudent {
public:
CStudent(char *n, int a);
~CStudent();
static void SetAge(int age);
private:
char *name;
int age;
static int nTotalObj;
};
int CStudent::nTotalObj = 0;
CStudent::CStudent(char *n, int a) : age(a) {
int nLen = strlen(n);
name = new char[nLen + 1];
strcpy(name, n);
name[nLen] = '\0';
nTotalObj++;
}
CStudent::~CStudent() {
delete[] name;
nTotalObj--;
}
void CStudent::SetAge(int age) {
this->age = age;
}
void main() {
CStudent stu1("张三", 25);
CStudent str2("李四", 26);
cout << "CStudent::nTotalObj=" << CStudent::nTotalObj << endl;
}
```
这样就能保证在对象被销毁时,其成员变量占用的内存也会被释放,避免了内存泄漏的问题。
阅读全文