运算符重载之加号运算符重载

2021-02-22 10:54:16 浏览数 (1)

加号运算符重载

运算符重载:对已有运算符的重新定义,赋予其另一种功能,以适应不同的数据类型

代码语言:javascript复制
#include<iostream>
using namespace std;
class pig{
public:
	int kilogram;   //重量
	int price;     //价钱
	//成员函数重载 号运算符
	//pig operator (pig& p)
	//{
	//	pig temp;
	//	temp.kilogram = this->kilogram   p.kilogram;
	//	temp.price = this->price   p.price;
	//	return temp; //不加return,存放在栈区的数据会在调用完之后直接释放
	//}
};
//全局函数重载加号
pig operator (pig& p1,pig& p2)
{
	pig temp;
	temp.kilogram = p1.kilogram   p2.kilogram;
	temp.price =p1.price   p2.price;
	return temp; //不加return,存放在栈区的数据会在调用完之后直接释放
}
//函数重载
pig operator (pig& p, int n)
{
	pig temp;
	temp.kilogram = p.kilogram   n;
	temp.price = p.price   n;
	return temp;//不加return,存放在栈区的数据会在调用完之后直接释放
}
void test01()
{
	pig p1, p2;
	p1.kilogram = 300;
	p1.price = 1000;
	p2.kilogram = 250;
	p2.price = 800;
	pig p3;
	p3 = p2   p1;
	cout << "p3猪的重量" << p3.kilogram << "  " << "p3猪的价钱" << p3.price << endl;
	//运算符重载,也可以发生函数重载
	p3 = p2   100; //perosn  int
	cout << "p3猪的重量" << p3.kilogram << "  " << "p3猪的价钱" << p3.price << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

0 人点赞