64,648
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<string.h>
using namespace std;
class Student
{
int age;
char *name;
public:
Student(int,char *);
Student();
Student(const Student &);//<------增加一个拷贝构造函数
~Student();
void SetName(int,char *);
int Getage(){return age;}
char *GetName(){return name;}
const Student &operator= (const Student &);//<--赋值运算符重载
};
Student::Student(int m,char *n)
{
cout<<"Paramater!"<<endl;
age=m;
name=new char[strlen(n)+1];
strcpy(name,n);
}
Student::Student()
{
cout<<"No paramater!"<<endl;
age=0;
char *n="baolun";
name=new char[strlen(n)+1];
strcpy(name,n);
}
Student::Student(const Student &t)//<----------here
{
age=t.age;
name=new char[strlen(t.name)+1];
strcpy(name,t.name);
}
Student::~Student()
{
cout<<"Free student!"<<endl;
delete []name;
}
void Student::SetName(int m ,char *n)
{
age=m;
name=new char(strlen(n)+1);
strcpy(name,n);
}
const Student &Student::operator= (const Student &Temp)//<--here
{
if (&Temp != this)
{
age=Temp.age;
delete [] name;
name=new char[strlen(Temp.name)+1];
strcpy(name,Temp.name);
}
return *this;
}
main()
{
int i;
Student stu[3];
stu[0]=Student();
stu[1]=Student(21,"yanhufen");
stu[2]=Student(19,"baocaomin");
/*Student stu[3]=
{
Student(),
Student(31,"sldjfl"),
Student(19,"baocaomin")
};*/
for(i=0;i<3;i++)
{
cout<<"Stu["<<i<<"]: ";
cout<<"Name:"<<stu[i].GetName()<<" ";
cout<<"Age:"<<stu[i].Getage()<<endl;
}
}