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; } }
相关文章推荐
- C++基本内置类型
- 重大发现: windows下C++ UI库 UI神器-SOUI(转载)
- leetcode_189_Rotate Array(easy)(C++)
- 使用C++实现工厂模式
- iOS OC语言: Block底层实现原理
- java的引用和c++的指针有什么区别
- C语言ASM汇编内嵌语法【转】
- C++标准库之stack(各函数及其使用全)
- C++的深拷贝与浅拷贝
- C、C++等语言常见符号作用总结
- 公司技术管理角度看C++游戏程序员发展
- C语言#自动生成四则运算的编程
- 通过模板的特化实现 简单的类型萃取 实现memcppy时候对于特殊类型如string类的拷贝。
- java与c++程序在编译和运行上有什么区别
- 【C++】《C++标准程序库》小结第六章(容器)
- C语言学习笔记
- 线程池原理及创建(C++实现)
- C++标准库之vector(各函数及其使用全)
- 重新学习《C++Primer5》第15章-面向对象程序设计
- 你好,C++(12)怎样管理多个类型同样性质同样的数据?3.6 数组