详解c/c++赋值函数(重载=号运算符)

2020-01-06 19:17:43于丽

首先c++里的各种运算符都是用函数实现的,比如=,就等号函数。

所以当用=给一个对象赋值的时候,实际调用的是=号所对应的=号函数。

分析下面的代码


#include <iostream>
using namespace std;
class Test{
public:
 explicit Test(){
  data = 0;
 }
 explicit Test(int d):data(d){
  cout << "C:" << this << ":"<< this->data << endl;
 }
 //拷贝构造函数                            
 Test(const Test &t){
  cout << "Copy:" << this << endl;
  data = t.data;
 }
 //重载=号运算符                      
 Test& operator= (const Test &t){
  cout << "assign" << this << endl;
  if(this != &t){
   data = t.data;
  }
  return *this;
 }
 ~Test(){
  cout << "F:" << this << ":" << this->data << endl;
 }
private:
 int data;
};
int main(){
 Test t1(10);
 Test t2, t3;
 t3 = t2 = t1;
 return 0;
}

重点分析下面的函数


 //重载=号运算符                      
 Test& operator = (const Test &t){
  cout << "assign" << this << endl;
  if(this != &t){
   data = t.data;
  }
  return *this;
 }

分析点:

1,operator =是什么意思

2,参数为什么是引用类型

3,参数为什么有const限制

4,为什么有if(this != &t)的判断

5,为什么有返回值