等号操作符重载

等号操作符重载

1620743144288

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>


using namespace std;

class Student
{
public:
Student();
Student(const char * tname);
Student(const Student & s);
~Student();

//重载赋值运算符
Student & operator=(const Student & s);
friend ostream & operator<<(ostream & cout ,const Student & s);
static long long sid;
private:
char * name;
int nameLen;

long long id;
};

long long Student::sid = 10000000;
//操作赋值操作符
Student & Student::operator=(const Student & s)
{
//首先判断是不是本身
if (&s == this)
{
return *this;
}
//判断是否为空,如果不为空,就将自身开辟的空间释放掉

if (this->name != NULL)
{
delete[] this -> name;
this -> name = NULL;
}

//执行深拷贝
this->nameLen = s.nameLen;
this -> name = new char[this->nameLen + 1];
strcpy(this->name,s.name);
this->id = s.id;
return *this;
}


//拷贝构造函数
Student::Student(const Student & s)
{
nameLen = s.nameLen;
id = s.id;
cout << Student::sid << endl;
if (s.name == NULL)
{
name = NULL;
return;
}
name = new char[nameLen + 1];
strcpy(name, s.name);

}


ostream & operator<<(ostream & cout, const Student & s)
{
if (s.name == NULL)
{
cout << "学号为"<<s.id<<"该学生无效" << endl;
return cout;
}
cout <<"姓名:" << s.name << endl;
cout <<"学号:" << s.id << endl;
cout << "====================" << endl;
return cout;
}

Student::Student(const char * tname)
{
nameLen = strlen(tname);
id = ++sid;

name = new char[nameLen + 1];

strcpy(name,tname);
}

Student::Student()
{
name = NULL;
nameLen = 0;
id = ++sid;
}

Student::~Student()
{
if (sid > 10000000)
{
--sid;
}

if (name != NULL)
{
cout << name << " 0x" << (int *)name << " 已被析构" << endl;
delete[] name;
name = NULL;
}else
cout << "NULL" << " 0x" << (int *)name << " 已被析构" << endl;

}

int main(char *argv[], int argc)
{
Student s1, s2("XiaoMing");

cout << s1 << s2 << endl;

s1 = s2;
cout << s1 << endl;

return 0;
}

1620743161702