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++预定义的操作符。

       运算结果如下:

 

猜你喜欢

转载自blog.csdn.net/weixin_41440777/article/details/84640206