1. 程式人生 > >C++的運算子的過載函式的使用

C++的運算子的過載函式的使用

       過載函式是用來處理函式功能類似但引數的資料型別不同的問題,即使用同名函式宣告各種不同功能,但是這些同名的函式的形式引數(引數的個數、型別和順序)必須不同。本文主要介紹構運算子的過載函式的構造。

       先上程式碼,本程式碼是構造兩個(a,b,c)格式的 引數之間的加減乘運算,並輸出(x,y,z)格式的運算結果。

#include <iostream>
using namespace std;

struct Point {
	int x, y, z;
	Point(int x = 0, int y = 0, int z = 0) :x(x), y(y) ,z(z) {}//建構函式
};

Point operator + (const Point& A, const Point& B) //以函式成員過載+
{
return Point(A.x + B.x, A.y + B.y, A.z + B.z);
}

ostream& operator << (ostream &out, const Point& p){//命名輸出格式
	out << "(" << p.x << "," << p.y << "," << p.z << ")";
	return out;
}

 Point operator - (const Point &A, const Point &B)    //以函式成員過載-
{
	 return Point(A.x - B.x, A.y - B.y, A.z - B.z);
}

 Point operator * (const Point &A, const Point &B)    //以函式成員過載-
 {
	 return Point(A.x * A.y * A.z, B.x * B.y * B.z);
 }

int main()
{
	Point a(7,8,7), b(1.6, 2,5);
	cout << a-b << a+b << a*b << endl;
	system("pause");
	return 0;
}

       程式碼中先建構函式Point,利用operator過載運算子+,-,*等符號,過載的操作符在類體中被宣告,宣告方式如同普通成員函式一樣,只不過他的名字包含關鍵字operator,以及緊跟其後的一個c++預定義的操作符。

       運算結果如下: