close

 重載運算子

 

 

C++中,預設除了基本資料型態可以使用運算子進行運算,例如: int,double,char..etc,如果你要將兩個物件(object)相加,預設是不可行的。

 

然而很多情況下,你會想要將兩個object的某些屬性值相加,並且回傳運算的結果,其實這發生情況頻率還蠻大的,例如: 座標的相加,如果你定義了一個Point2D類別,當中有x & y 兩個屬性成員,你會想要透過+- 的動作來得到兩個座標相加或相減或相乘,甚至於判斷是否等值,在C++中,這些動作,你都可以透過重載運算子來完成。

 

接下來,我們來寫點code吧 ! 

#include<iostream>
using namespace std;

class Point2D 
{
public:
	Point2D();
	Point2D(int, int);
	int x() { return _x; }
	int y() { return _y; }
	Point2D operator+(const Point2D&);	 // 重載+運算子 
	Point2D operator-(const Point2D&);	 // 重載-運算子 
	Point2D& operator++();				 // 重載++前置,例如 ++p 
	Point2D operator++(int);			 // 重載++後置,例如 p++
	Point2D& operator--();				 // 重載--前置,例如 --p 
	Point2D operator--(int);			 // 重載--後置,例如 p--
	
	bool operator==(const Point2D&);
 
private:
	int _x;
	int _y;
};

Point2D::Point2D()
		:_x(0), 
		 _y(0)
{
}
Point2D::Point2D(int x, int y)
		: _x(x), _y(y)
{
}
Point2D Point2D::operator+(const Point2D &p) {
	Point2D tmp(_x + p._x, _y + p._y);
	return tmp;
}

Point2D Point2D::operator-(const Point2D &p) {
	Point2D tmp(_x - p._x, _y - p._y);
	return tmp;
}

Point2D& Point2D::operator++() {
	_x++;
	_y++;

	return *this;
}

Point2D Point2D::operator++(int) {
	Point2D tmp(_x, _y);
	_x++;
	_y++;

	return tmp;
}

Point2D& Point2D::operator--() {
	_x--;
	_y--;

	return *this;
}

Point2D Point2D::operator--(int) {
	Point2D tmp(_x, _y);
	_x--;
	_y--;

	return tmp;
}

bool Point2D::operator==(const Point2D &p)
{
	if (_x == p._x && _y == p._y)
		return true;
	return false;

}


int main()
{
	Point2D p1(5, 5);
	Point2D p2(10, 10);
	Point2D p3;

	p3 = p1 + p2;
	cout << "p3(x, y) = ("
		<< p3.x() << ", " << p3.y()
		<< ")" << endl;

	p3 = p2 - p1;
	cout << "p3(x, y) = ("
		<< p3.x() << ", " << p3.y()
		<< ")" << endl;

	p3 = ++p1;
	cout << "p3(x, y) = ("
		<< p3.x() << ", " << p3.y()
		<< ")" << endl;


	bool bEqual = (p1 == p2);
	cout << "p1 == p2 ?  " << endl << "> ";
	bEqual == true ?
		cout << "Equal" << endl : cout << "No Equal" << endl;
	return 0;
}


 

執行結果: 

 

在重載+與-號運算子時,所接收的物件引數來自被重載的運算子右邊,例如在程式碼中加法運算時,+右邊是p2,所以傳入的物件引數就是p2物件,減法運算 時-號右邊是p1,所以傳入的就是p1物件,在傳入引數時,您使用傳參考的方式進行,這可以省去物件複製的動作,您也可以不使用傳參考,這對這個程式並不 造 成結果的差異,但使用傳參考方式可以節省CPU在複製物件時的處理時間。 

大部份的運算子都是可以被重載的,除了以下的運算子之外: 

.   ::   .*   ?:

 

 

arrow
arrow
    文章標籤
    C++ C operator
    全站熱搜

    Eric 發表在 痞客邦 留言(0) 人氣()