運算符重載:operator(翻譯:操作)
-
- 前置++
- const Human& operator ++() { ++i; (*p)++; return *this; } //傳回引用,防止值傳回時的記憶體開銷
- 注意:++a;相當于a.operator++(),相當于調用函數,有傳回值,也可以指派
- 後置++
- const Human operator ++(int) { Human old(*this); i++; (*p)++; return old;} //因為臨時作用域結束的時候,就會釋放,是以如果傳回引用是空,是以傳回值。
- 加減+ / -
- const Human operator +(const Human &r){return Human(i + r.geti(),*p+r.getp());} //用const修飾形參,則需要r對象調用的函數要被const修飾,如:int get () const;
- 指派=
- const Human &operator =(const Human &r) { if (this==&r) { return *this;} i = r.geti(); *p = r.getp();return *this; }
- 指派運算符重載不用開辟空間,而複制構造函數可以當做構造函數使用,要開辟空間。
- 轉換類型運算符
- operator int() { return i; } //調用時 Human man;int x=int(man);或者int x=(man);或者int x=man;
- 下标[]
- char &operator [](int index) { if (index >= 0 && index < length) { return size[index]; } else { cout << "超出範圍" << endl; return size[length]; } }
- 注意:
- 由于函數的參數即是數組的下标,是以該函數隻能帶一個參數,不可帶多個參數。
- 由于下标運算符函數隻限于本類的對象使用,是以不得将下标運算符函數重載為友元函數,且必須是非static類的成員函數。
- <<:編譯器判斷<<左邊是ostream的對象,就認為是輸出;左邊不是ostream的對象,就認為是位移操作符
- 普通函數:ostream& operator <<(ostream &out, const Human&man) { out << man.age << endl; out << man.heither << endl; return out;//由于cout是另一個類ostream的對象,ostream類沒有公共的構造函數, //是以函數無法調用該類的複制構造函數,必須按引用的方法接受ostream的對象,并按引用的方式傳回ostream對象 }
- 友元函數:friend ostream& operator <<(ostream &out, const Human&man)//因為該函數含有其他類的對象,是以這個函數就不能成為類Human的成員函數。加friend可以解決這個問題 { out << man.age << endl; out << man.heither << endl; return out; }
- >>
- friend istream& operator >>(istream &in, Human&man)//因為該函數含有其他類的對象,是以這個函數就不能成為類Human的成員函數。加friend可以解決這個問題 { in >> man.age; in >> man.heither; return in; }
- C++的運算符大部分可以被重載,但是有一些卻不能重載。如“.”,"::","*","? :","#".
- “.”,"::","*"在c++中有特殊的意義,假如重載的話會引起一些麻煩。
- "#"是預處理标志,而不是運算符
- "? :"沒有确定性,重載沒有意義
- 前置++