(原創) 如何使用Operator Overloading? (C/C++)
Abstract
Operator Overloading讓我們可以自己定義Operator的功能,讓程式可以更精簡,C#也有,不過不是很強調,但C++非常強調Operator Overloading,這是C++的一大特色。
Introduction
以下程式我們試著實做一個『複數』型別,複數由實部,有虛部,複數的加法為(a + bi) + (c +di) = (a +c) + (b+d)i,乘法則是(a + bi) * (c+di) = (ac - bd) + (ad + bc) i。
C++
(C) OOMusou 2006 http://oomusou.cnblogs.com
Filename : OperatorOverloading.cpp
Compiler : Visual C++ 8.0 / ISO C++
Description : Demo how to use use Operator Overloading
Release : 10/16/2007 2.0
*/
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double re = 0.0, double im = 0.0) : re(re), im(im) {}
public:
Complex operator+(const Complex&); // use member function
friend Complex operator*(const Complex&, const Complex&); // use global function
friend ostream& operator<<(ostream&, const Complex&); // use global function
private:
double re; // real part
double im; // imagenary part
};
Complex Complex::operator+(const Complex& complex) {
Complex _complex;
_complex.re = this->re + complex.re;
_complex.im = this->im + complex.im;
return _complex;
}
Complex operator*(const Complex& complex1, const Complex& complex2) {
Complex _complex;
_complex.re = complex1.re * complex2.re - complex1.im * complex2.im;
_complex.im = complex1.re * complex2.im + complex1.im * complex2.re;
return _complex;
}
ostream& operator<<(ostream& out, const Complex& complex) {
out << "real:" << complex.re << " imagenary:" << complex.im;
return out;
}
int main() {
Complex complex1(2,2);
Complex complex2(3,3);
Complex complex3 = complex1 + complex2;
Complex complex4 = complex1 * complex2;
cout << complex3 << endl;
cout << complex4 << endl;
}
執行結果
real:0 imagenary:12
第17行使用member function的方式overload + operator,18行使用global function的方式overload * operator,這兩種寫法都可以,惟若使用global function,由於要存取data menber,所以要宣告該function為friend,這樣才能存取data member。
19行我們overload了<< operator,由於也是global function,所以也要宣告friend。
最後49行和55行的user code,直接用+和*就可以計算複數,而且cout也直接支援Complex物件,非常清楚,這就是operator overloading的威力,不過,在class implementation時,operator overloading的語法不是很好寫,雖然語法很有邏輯很有道理,但就是太臭太長了,還真的得時間熟悉才行。
See Also
(原創) 如何對複數進行運算 ? (C/C++)