企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
为什么operator=返回一个`reference to *this `? 为了实现连续赋值,赋值操作符必须返回一个引用指向操作符的左侧实参。这是你为class实现赋值操作符必须遵循的协议。这个协议不仅适用于标准的赋值形式,也适用于+=、-=、*=等等。 注意,这只是一个协议,并无请执行。如果不遵循它,可能代码一样通过编译。然而这份协议被所有内置类型和标准程序库所提供的类型如string、vector等所遵守。因此除非你有一个标新立异的好理由,不然还是随众吧。 --- 如果没有重载赋值运算符,编译器会自动创建默认的赋值运算符重载函数。行为类似默认拷贝构造,进行简单值拷贝。 --- ~~~ #include <iostream> using namespace std; class Student { public: Student(const char *name) { pName = new char[strlen(name) + 1]; strcpy(pName, name); } //防止浅拷贝 Student(const Student &stu) { cout << "拷贝构造" << endl; pName = new char[strlen(stu.pName) + 1]; strcpy(pName, stu.pName); } //重写赋值运算符重载 Student &operator=(const Student &stu) { //不确定this->pName的空间是否能装下stu中数据,所以先释放 if(this->pName != NULL) { delete[] this->pName; this->pName = NULL; } //申请堆区空间,大小由stu决定 this->pName = new char[strlen(stu.pName) + 1]; //拷贝数据 strcpy(this->pName, stu.pName); //返回对象本身 return *this; } ~Student() { if (pName != NULL) { delete[] pName; pName = NULL; } } void printStudent() { cout << "Name: " << pName << endl; } public: char *pName; }; void test02() { Student s1("x"); Student s2("jd"); s1.printStudent(); s2.printStudent(); s1 = s2; s1.printStudent(); } int main() { test02(); getchar(); return EXIT_SUCCESS; } ~~~