operator+
例如:
const Complex operator+(const Complex &obj); //member function
使用const+參考是為了效率。
還可以寫成friend function:
friend Comples operator+(Complex &o1,Complex &o2);
記得在外部定義即可:
Complex operator+(Complex &o1,Complex &o2)
{
return Complex(o1.real+o2.real,o1.imag+o2.imag); // 回傳沒有名字的物件
}
(note:
由上面的例子可得知,constructor本身並非void function,它會回傳沒有名字的物件。)
上面討論的都是 c3=c1+c2,也就是兩個參數都是object的時候。
如果是c3=c1+x呢?(x為任意int)
Complex Complex::operator+(int& x); //裡面傳的參數資料型態改一下
如果是c3=x+c2呢?
原本上面兩個狀況都是由c1這個物件呼叫operator+這個函式,有點像c1.operator+(c2)的感覺,所以才用member function。
現在則沒有物件能呼叫了,所以才用外部定義的friend function。
Complex operator+(int& x,Complex& o);
(note:
c3=(c1+c2) // c3 和 (c1+c2) 是不同物件。(c1+c2)是一個沒有名字的物件,它的值會被拿去給c3)
operator++
有prefix跟postfix兩種,為了區別於是寫法如下,只差在有沒有再傳參數進去。
Point& operator++() // prefix
{
count++;
return *this;
}
(note: 回傳值為參考)
Point operator++(int n) // postfix
{
Point tmp=*this;
this->count++;
return tmp;
}
(note: postfix 的 operator++回傳值不是參考!!否則會出現錯誤訊息:"warning: reference to local variable ‘result’ returned [-Wreturn-local-addr] ",因為若回傳tmp參考,tmp本身會再動作結束後消失造成錯誤!!)
可以簡化來看:
operator++()
operator++(int)
值得注意的是為何postfix operator需要額外的傳int進去呢?這是因為C++判斷function的時候,是由它們的signature,也就是參數數量、型別與順序,而非回傳值來看。參考:overloading postfix and prefix operators
(the function overloading can be achieved by different data type and different number of argument list, but it cannot be different return type.)
operator>> & <<
friend istream& operator>>(istream& in,Complex &c)
{
in>>c.real>>c.imag;
return in;
}
friend ostream& operator<<(ostream& out,Complex &c)
{
out<<c.real<<" "<<c.imag<<endl;
return out;
}
(note:return in跟return out是為了連續輸入/輸出)
沒有留言:
張貼留言