一般運算符重載
在進行對象之間的運算時,程序會調用與運算符相對應的函數進行處理,所以運算符重載有兩種方式:成員函數和友元函數。成員函數的形式比較簡單,就是在類裡面定義了一個與操作符相關的函數。友元函數因為沒有this指針,所以形參會多一個。
// 運算符重載,這裡又叫賦值函數 string& operator =(const string &other); // 運算符重載,但這裡要用友元函數才行 friend ostream& operator << (ostream &os,const string &str); string &string::operator=(const string &other) { if(this == &other) return *this; delete []m_data; m_data = NULL; m_data = new char[strlen(other.m_data)+1]; strcpy(m_data,other.m_data); return *this; } ostream& operator << (ostream &os,const string& str) // 返回引用用於實現鏈式表達式 { os<<str.m_data; return os; }
成員函數重載與友元函數重載的區別:
If you define your operator overloaded function as member function, then compiler translates expressions like s1 + s2
into s1.operator+(s2)
. That means, the operator overloaded member function gets invoked on the first operand. That is how member functions work!
But what if the first operand is not a class? There's a major problem if we want to overload an operator where the first operand is not a class type, rather say double
. So you cannot write like this 10.0 + s2
. However, you can write operator overloaded member function for expressions like s1 + 10.0
.
To solve this ordering problem, we define operator overloaded function as friend
IF it needs to access private
members. Make it friend
ONLY when it needs to access private members. Otherwise simply make it non-friend non-member function to improve encapsulation!
兩種重載方式的比較:
注意事項: