您的位置:首页 > 编程语言 > C语言/C++

C++二目运算符重载

2016-03-16 14:17 239 查看
/*======================================================================
模板:
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: