#include <iostream>
#include <cstring>
using namespace std;
class Student {
public:
Student() {
this->id = 0;
this->name = nullptr;
}
//注意构造函数重新分配内存
Student(int id, char *name) {
this->id = id;
int len = strlen(name);
this->name = new char[len + 1];
strcpy(this->name, name);
}
//拷贝构造也一样重新分配内存
Student(const Student &another){
this->id = another.id;
int len = strlen(another.name);
this->name = new char[len+1];
strcpy(this->name, another.name);
}
//重载等号操作符
Student& operator=(const Student &another){
//防止自己=自己
if (this==&another){
return *this;
}
//清空自身的指针开辟出的空间
if (this->name != nullptr){
delete[] this->name;
this->name = nullptr;
this->id = 0;
}
//深拷贝
this ->id = another.id;
int len =strlen(another.name);
this->name = new char[len+1];
strcpy(this->name, another.name);
return *this;
}
~Student(){
if (this->name != nullptr){
delete[] this->name;
this->name = nullptr;
this->id = 0;
}
}
private:
int id;
char *name;
};
int main() {
Student a1;
Student a2(4,"ggG");
a1 = a2;
std::cout << "Hello, World!" << std::endl;
return 0;
}
=操作符重载(指针型)
最新推荐文章于 2024-07-26 20:29:14 发布