|
#pragma once
#include <string>
#include <iostream>
using namespace std;
class cstudent
{
public:
char* pname;
char sex;
int age;
int num;
cstudent();//构造函数
cstudent(char* t_name,char t_sex,int t_age,int t_num);
cstudent& operator=(const cstudent& stu);
~cstudent();//析构函数
};
#include "cstudent.h"
cstudent::cstudent()
{
pname=NULL;//这个不能少。为什么,
};
cstudent::cstudent(char* t_name,char t_sex,int t_age,int t_num):sex(t_sex),num(t_num),age(t_age)
{
int n_len=strlen(t_name);
pname=new char[n_len+1];
memset(pname,0,n_len+1);
strcpy(pname,t_name);
};
cstudent& cstudent::operator=(const cstudent& stu)
{
sex=stu.sex;
num=stu.num;
age=stu.age;
if(pname)
{
delete [] pname;
pname=NULL;
}
int name_len=strlen(stu.pname)+1;
pname=new char[name_len];
memset(pname,0,name_len);
strcpy(pname,stu.pname);//把名子赋值过来
return *this;
};
#include <string>
#include <iostream>
#include "cstudent.h"
using namespace std;
void test()
{
cstudent stu01("zhangsan",'m',15,1002);
cstudent stu02;
stu02=stu01;//程序会出错,因为定义俩个对象后析构两次释放两次内存报错,要用运算符重载。
}
int main()
{
test();
return 0;
}
上面的构造函数里面必须有pname=NULL;否则程序会报错。其他代码和syc老师上课讲的一样,后来才发现是这里错了。 |
上一篇: MFC总是无法下载下一篇: 电脑端页面链接不上
|