初学者,指针问题。

dragonxf 2008-10-30 05:30:59
这是我在学习中的一个程序,当前是运行成功的。问题在注释中,可以不用关心主函数中的内容

#include <iostream.h>
#include <string.h>
#include <math.h>

class CStudent
{
private:
int number;
char name[10]; // 如果此句改为:char *name;构造函数
static int total; //该如何编写。
public:
CStudent(int num,char *na);
~CStudent();
int GetTotal();
int GetNumber();
};

CStudent::CStudent(int num,char *na) //此处是需要更改的对方
{
number=num;
strcpy(name,na);
total++;
}

CStudent::~CStudent()
{
total--;
}

int CStudent::GetNumber()
{
return number;
}

int CStudent::GetTotal()
{
return total;
}
int CStudent::total=0; //静态数据成员,在类中声明,还要在程序中定义。
void fun();

void main()
{
CStudent s1(1001,"tom");
cout<<s1.GetNumber()<<endl;
cout<<s1.GetTotal()<<endl;

CStudent s2(1002,"lily");
cout<<s2.GetNumber()<<endl;
cout<<s2.GetTotal()<<endl;

cout<<s1.GetTotal()<<endl;

fun(); //在对象作用结束后自动调用析构函数;;

cout<<s1.GetNumber()<<endl;
cout<<s1.GetTotal()<<endl;

}

void fun()
{
CStudent s3(1003, "bob" );
cout << s3.GetNumber() << endl;
cout << s3.GetTotal() << endl;

}
...全文
74 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dragonxf 2008-10-30
  • 打赏
  • 举报
回复
此贴已结。
wlamos 2008-10-30
  • 打赏
  • 举报
回复
构造函数中自己分配内存,析构函数中释放即可
wuyu637 2008-10-30
  • 打赏
  • 举报
回复
CStudent::CStudent(int num,char *na) //此处是需要更改的对方
{
number=num;
int length = strlen(na);
name = new char[length+1];
strcpy(name,na);
name[length] = '\0';
total++;
}

CStudent::~CStudent()
{
delete []name;
total--;
}

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧