C++等號操作符重載


在新學操作符重載時最令人頭疼的可能就是一些堆溢出的問題了,不過呢,只要一步步的寫好new 與 delete。絕對不會有類似的問題。

當時我們編譯可以通過,但是運行會出錯,因為對象s1與s2進行賦值時,采用淺拷貝,導致對象析構時會對同一塊內存空間析構兩次。也就是說等號操作符“=”,默認是進行淺拷貝,我們需要對等號操作符進行重載,使其能夠進行深拷貝。

同時要重載等號操作符支持鏈式編程,類如 s3 = s4 = s5;  //操作符使對象連載疊加,與上一篇的return *this 與 return this已經介紹過如何返回對象本身。而不是克隆。

這里寫了 重載等號操作符實現深拷貝 與 操作符使對象連載疊加 的代碼。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<string.h>
#include<windows.h>
using namespace std;
class student
{
public:
 student()
 {
  //默認構造函數
  cout << "This is studnt();" << endl;
  this->id = 0;
  this->name = NULL;
 }
 student(int id, const 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)
 {
  // 1.防止自身賦值
  if (this == &another)
  {
   return *this;
  }
  // 2. 給自己額外開辟的內存空間釋放掉
  if (this->name != NULL)
  {
   delete[] this->name;
   this->name = NULL;
   this->id = 0;
  }
  //3. 執行深拷貝
  this->id = another.id;
  int len = strlen(another.name);
  this->name = new char[len + 1];
  strcpy(this->name, another.name);
  return *this;
 }
 void printf_id_name()
 {
  cout << "id= " << id << " name= " << name << endl;
 }
 ~student()
 {
  if (this->name != NULL)
  {
   delete[] this->name;
   this->name = NULL;
   this->id = 0;
  }
 }
private:
 int id;
 char *name;
};

int main(void)
{
 student s1(1, "C++");
 student s2;
 student s3(3, "ZJD666");
 
 s2=s3; //深拷貝 等號操作符重載
 s1.printf_id_name();
 s2.printf_id_name();
 s3.printf_id_name();
 cout <<" --------------------------" << endl;
 student s4(4, "Hello World!");
 student s5(5, "Hello C++!");
 s3 = s4 = s5;  //操作符連載
 s3.printf_id_name();
 system("pause");
 return 0;
}

供學習等號操作符重載參考!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM