Problem Description
一个学生类Student,它有2个数据成员,姓名char* name 、年龄int age。编写这个类的代码。
完善以下程序
//你的代码写在这里
Student::~Student()
{
delete name;
}
int main()
{
Student s1(“czg”, 18), s2;
s2 = s1;
s1.Display();
s2.Display();
return 0;
}
Input Description
无
Sample Output
czg 18
czg 18
#include <iostream>
using namespace std;
#include <string>
class Student
{
public:
string * name;
int * age;
Student(string a, int b)
{
name = new string(a);//将a创建在堆区,并让指针name去维护堆区
age = new int(b);
}
//堆区需要手动释放,即析构函数
Student()
{
//判断不为空,则释放
if (age != NULL && name != NULL)
{
delete age,name;
age = NULL;
name = NULL;
}
}
//赋值重载
Student& operator=(Student &p)
{
//编译器提供的重载:name = p.name; 默认浅拷贝
/*
* 判断是否有属性在堆区,有先释放干净,再深拷贝
if (age != NULL && name != NULL)
{
delete age, name;
age = NULL;
name = NULL;
}
*/
//深拷贝 新在堆区开辟一空间,防止堆区内存重复释放,程序崩溃
name = new string(*p.name);
age = new int(*p.age);
//返回对象本身,连续赋值
return *this;
}
//输出
void Display()
{
cout << *name << " " << *age << endl;
}
~Student();
};
Student::~Student()
{
delete name;
}
int main()
{
Student s1("czg", 18), s2;
s2 = s1;
s1.Display();
s2.Display();
return 0;
}
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
class Student
{
public:
char *name;
int age;
Student(const char *a="",int b=0)
{
name=new char[strlen(a)+1];
strcpy(name,a);
age=b;
}
Student& operator=(const Student& s)
{
name=new char[strlen(s.name)+1];
strcpy(name,s.name);
age=s.age;
}
~Student();
void Display()
{
cout<<name<<" "<<age<<endl;
}
};
Student::~Student()
{
delete name;
}
int main()
{
Student s1("czg", 18), s2;
s2 = s1;
s1.Display();
s2.Display();
return 0;
}