我在一開始學習C++編程時,對“運算符重載”這裏一直很迷惑。例如對於輸出運算符的重載,我剛開始是這樣想的:C++明明提供了<<來進行輸出,爲什麼還要重載一個呢?最後我通過查資料,結合我的理解,通俗地說:重載可以理解爲“自己重寫寫”,因爲C++提供的某些運算符並不能完全滿足我們日常的編程需求,所以就要程序員自己寫函數來實現某些運算符的要求。 例如,對於複數 1+2i,C++自帶的輸出<<是無法正確操作的,因爲這個複數是自定義類型(沒有形如a+bi的數據類型)。要是有表述不清楚的,請讀者指正。以下就是我基於複數的一些操作進行的運算符重載的測試,測試環境爲VS2013
#include <iostream>
#include <stdlib.h>
using namespace std;
class Complex
{
private:
double _real;
double _img;
friend ostream& operator<<(ostream& _cout, const Complex& c);
friend istream& operator>>(istream& _cin, Complex& c);
public:
//構造函數
Complex(double real = 0, double img = 0)
{
//cout << "構造函數~" << endl;
_real = real;
_img = img;
}
//拷貝構造函數
Complex(Complex& c)
{
//cout << "拷貝構造函數~" << endl;
_real = c._real;
_img = c._img;
}
//析構函數
~Complex()
{}
//賦值運算符重載
Complex& operator=(Complex& c)
{
if(this != &c)
{
_real = c._real;
_img = c._img;
return *this;
}
}
//+=重載
Complex& operator+=(Complex& c)
{
_real += c._real;
_img += c._img;
return *this;
}
//-=重載
Complex& operator-=(Complex& c)
{
_real -= c._real;
_img -= c._img;
return *this;
}
};
//輸入運算符重載
istream& operator>>(istream& _cin, Complex& c)
{
cout << "請輸入實部:";
_cin >> c._real;
cout << "請輸入虛部:";
_cin >> c._img;
return _cin;
}
//輸出運算符重載
ostream& operator<<(ostream& _cout, const Complex&c)
{
if (c._img > 0)
{
_cout << c._real << "+" << c._img << "i" << endl;
return _cout;
}
else if (c._img == 0)
{
_cout << c._real << endl;
return _cout;
}
else
{
_cout << c._real << c._img << "i" << endl;
return _cout;
}
}
void Test()
{
//調用構造函數
Complex com1(4.0, 3.0);
cout <<"com1:"<< com1 << endl;
//調用拷貝構造函數
Complex com2(com1);
//輸出運算符重載
cout << "com2:" << com2 << endl;
Complex com3;
//測試輸入運算符重載
cin >> com3;
cout << "com3:" << com3;
Complex com4;
//測試賦值運算符重載
com4 = com3; //亦可以進行連續賦值,com4 = com3 = com1,則com4爲 1+2i;
cout << "com4:" << com4;
Complex com5(1.0, 2.0);
//測試+=運算符重載
com5 += com1;
cout << "com5:" << com5;
Complex com6(2.0, 1.0);
com6 -= com1;
cout << "com6:" << com6;
}
int main()
{
Test();
system("pause");
return 0;
}