C++二目运算符重载

/*======================================================================
模板:
1、模板函数 <-----> 模板类
|
v
标准模板类
2、友元函数			友元类
3、静态成员函数		静态数据成员
4、运算符重载
========================================================================
运算符重载
	二元运算符重载
		+号运算符 成员函数重载传入一个参数作为第二个参数  第一个参数默认是当前对象的参数
		输出运算符  第一个参数必须是ostream 所以不能是默认的对象参数 不能使用成员函数进行重载
		[]索引运算符  不能使用友元函数重载 因为第一个参数必须是当前对象的this指针。
=======================================================================*/
#include <iostream>
#include <string>
using namespace std;
class Coordinate
{
public:
	friend Coordinate operator ^ (Coordinate &coor1, Coordinate &coor2);
	friend ostream &operator<<(ostream &c1, Coordinate &c2);
	Coordinate(int x, int y)
	{
		m_iX = x;
		m_iY = y;
	}
	//这里传入参数最好是引用 如果用指针的话 调用的时候+后面的对象要进行取地址
	Coordinate operator+(Coordinate &coor)
	{
		Coordinate temp(0,0);
		temp.m_iX = this->m_iX + coor.m_iX;
		temp.m_iY = this->m_iY + coor.m_iY;
		return temp;
	}
	int operator[](int index)
	{
		if (index == 0)
			return this->m_iX;
		if (index == 1)
			return this->m_iY;
		else
			throw string("未索引到!");
	}
	void print()
	{
		cout << m_iX << "	" << m_iY << endl;
	}
private:
	int m_iX;
	int m_iY;
};
ostream &operator<<(ostream &c1, Coordinate &c2)
{
	c1 << c2.m_iX << "  " << c2.m_iY << endl;
	return c1;
}
Coordinate operator ^(Coordinate &coor1, Coordinate &coor2)
{
	Coordinate temp(1, 1);
	for (size_t i = 0; i < coor2.m_iX;i++)
		temp.m_iX = coor1.m_iX*temp.m_iX;
	for (size_t i = 0; i < coor2.m_iY; i++)
		temp.m_iY = coor1.m_iY*temp.m_iY;
	return temp;
}
int main()
{
	Coordinate coor1(4, 2),coor2(5,6);
	Coordinate coor3 = coor1 ^ coor2;
	//coor3.print();
	cout << coor3;//相当于写成了operator<<(cout,coor3);
	try{
		cout << coor3[2] << endl;
	}catch(string s){
		cout << s << endl;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值