定义一个学生类,包括姓名,姓名长度,年龄,性别。写出该类的构造函数、拷贝构造函数、析构函数;并重载=

2025-02-22 23:56:40
推荐回答(2个)
回答1:

#include
#include
using namespace std;

class Student
{
public:
Student(char*, int, bool);
Student(const Student&);
~Student();
Student& operator =(const Student&);
void print();
private:
char* name;
int age;
bool sex;
int len;
};

Student::Student(char* name, int age, bool sex)
{
len = strlen(name);
this->name = new char[len+1];
strcpy(this->name, name);
this->age = age;
this->sex = sex;
}

Student::Student(const Student& stu)
{
len = strlen(stu.name);
this->name = new char[len+1];
strcpy(this->name, stu.name);
this->age = stu.age;
this->sex = stu.sex;
}

Student::~Student()
{
len = 0;
delete[] name;
}

Student& Student::operator =(const Student& stu)
{
len = strlen(stu.name);
this->name = new char[len+1];
strcpy(this->name, stu.name);
this->age = stu.age;
this->sex = stu.sex;
return *this;
}

void Student::print()
{
cout << name << '\t';
if (sex) cout << "男";
else cout << "女";
cout << '\t' << age << endl;
}

int main()
{
Student s1("张三", 20, true);
Student s2(s1);
Student s3 = s1;
s1.print();
s2.print();
s3.print();
return 0;
}

回答2:

上面的回答很好,我就不答了,谢谢关注