运算符重载:对已有运算符的重新定义,赋予其另一种功能,以适应不同的数据类型
#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;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有