运算符重载

5、小作业:
为 CStudent 类重载 == 和 != 运算符,判断两个 CStudent 对象是否相等,或者说是否是同一个学生的数据。

#include <iostream>
using namespace std;
class Student
{
public:
    char* p_name;
    char sex;
    unsigned int age;
    Student(char* t_name, char t_sex, unsigned int t_age):sex(t_sex), age(t_age)
    {
        p_name = NULL;
        int str_len = strlen(t_name) + 1;
        p_name = new char[str_len];
        memset(p_name, 0, str_len);
        strcpy(p_name, t_name);
    }
    Student(const Student& stu)
    {
        int str_len = 0;
        if (stu.p_name)str_len = strlen(stu.p_name) + 1;
        this->p_name = NULL;
        if (str_len > 0)
        {
            this->p_name = new char[str_len];
            memset(this->p_name, 0, str_len);
            strcpy(this->p_name, stu.p_name);
        }
        this->sex = stu.sex;
        this->age = stu.age;
    }
    bool Student::operator==(const Student& stu)
    {
        if (p_name == stu.p_name && sex == stu.sex && age == stu.age)
        {
            cout << "姓名,性别,年龄都一样" << endl;
            return true;
        }
        else
        {
            cout << "姓名,性别,年龄存在不一样" << endl;
            return false;
        }
    }
    bool Student::operator!=(const Student& stu)
    {
        if (p_name != stu.p_name && sex != stu.sex && age != stu.age)
        {
            cout << "姓名,性别,年龄都不一样" << endl;
            return true;
        }
        else
        {
            cout << "姓名,性别,年龄存在一样" << endl;
            return false;
        }
    }
    ~Student()
    {
        delete[] p_name;
    }
};
void test()
{
    Student student_1 = { "zhangsan",'m',15 };
    Student student_2 = student_1;
    Student student_3 = { "aaww",'f',15 };
    bool t = student_2 != student_3;
    cout << t << endl;
}
int main()
{
    test();
    return 0;
}

 

posted on 2021-01-09 16:22  SakuraQAQ  阅读(79)  评论(0)    收藏  举报

导航