首先c++里的各種運(yùn)算符都是用函數(shù)實(shí)現(xiàn)的,比如=,就等號函數(shù)。
所以當(dāng)用=給一個(gè)對象賦值的時(shí)候,實(shí)際調(diào)用的是=號所對應(yīng)的=號函數(shù)。
分析下面的代碼
#include <iostream>using namespace std;class Test{public: explicit Test(){ data = 0; } explicit Test(int d):data(d){ cout << "C:" << this << ":"<< this->data << endl; } //拷貝構(gòu)造函數(shù) Test(const Test &t){ cout << "Copy:" << this << endl; data = t.data; } //重載=號運(yùn)算符 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;}重點(diǎn)分析下面的函數(shù)
//重載=號運(yùn)算符 Test& operator = (const Test &t){ cout << "assign" << this << endl; if(this != &t){ data = t.data; } return *this; }分析點(diǎn):
1,operator =是什么意思
2,參數(shù)為什么是引用類型
3,參數(shù)為什么有const限制
4,為什么有if(this != &t)的判斷
5,為什么有返回值
6,為什么返回值的類型是引用類型
分析點(diǎn)解答:
Test t2;
t2 = t1;//實(shí)際的運(yùn)作方式是t2.operator=(t1),所以函數(shù)里面的this就是t2
1,重載類Test的=號函數(shù),當(dāng)對類Test的對象用=號操作的時(shí)候,就會(huì)調(diào)用這個(gè)重載后的函數(shù)
2,避免調(diào)用拷貝構(gòu)造函數(shù)
3,避免不小心修改里參數(shù)t里面成員變量的值(t.data = 100;)
4,防止自己給自己賦值
5,為了能夠使用 t3 = t2 = t1。如果沒有返回值,則t3.operator=(t2=t1),的參數(shù)里面t2=t1就沒有返回值,所以編譯不過。
6,不是引用也可以,用引用類型是防止老版本的編譯器,在return處調(diào)用拷貝構(gòu)造函數(shù),新版本的編譯器(gcc 4.8.5-20),即使不用引用類型,就不會(huì)調(diào)用拷貝構(gòu)造函數(shù)。
總結(jié)
以上所述是小編給大家介紹的c/c++賦值函數(shù)(重載=號運(yùn)算符),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答