#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 发布
博客围绕=操作符的指针型重载展开,虽未给出具体内容,但核心聚焦于这一信息技术领域的操作符重载技术,该技术在编程中可实现特定功能,对程序设计有重要意义。
2548

被折叠的 条评论
为什么被折叠?



