【c++程序】符号的重载与友元
2015-10-22 20:40
381 查看
/********************************************************/ /**************---About 符号的重载-------**************/ /**************---Author: Tibruce Zhao-----**************/ /**************---Date: 2015/10/20------***************/ /********************************************************/ #include<iostream> using namespace std; class F { //private: int n; int d; //private: void reduce(){ int mcd=maxcd(n<0?-n:n,d); if(mcd!=1) n/=mcd,d/=mcd; } public: /*静态成员函数,使用不依赖某个类, *调用时,Type::func(),没有当前对象(this)。 */ static int maxcd(int a,int b){ if(a==0) return b; return maxcd(b%a,a); } F(int n=0,int d=1):n(n),d(d){ if(d==0) throw "分母不能为0.";//发现无法处理的异常,扔出去。 if(d<0) d=-d,n=-n; reduce(); cout<<"F("<<n<<'/'<<d<<")"<<endl; } friend ostream& operator<<(ostream& o,const F&f){ o<<f.n<<'/'<<f.d; return o; } friend F operator+(const F& lh,const F& rh){ F res(lh.n*rh.d+lh.d*rh.n,lh.d*rh.d); return res; } /*保证当前对象不被修改*/ F operator*(const F& rh)const{ return F (n*rh.n,d*rh.d);//匿名对象,因为用一次,提高效率 } }; int main() { F f1(6,8); F f2(6,-9); F f3(-6,12); cout<<f1<<','<<f2<<','<<f3<<endl; cout<<F::maxcd(392,856)<<endl; cout<<"*****************************"<<endl; cout<<f1+f2<<','<<f1+f3<<','<<f2+f3<<endl; cout<<f1+f2+f3<<endl; cout<<f3*f2<<endl; return 0; }
相关文章推荐
- 项目39.4-2 输出10000以内的所有回文数。
- 项目39.4-1输入一个正整数,判断其是否为一个回文数(例1221、12321都是回文数,正着看、倒着看,是同一个数)。
- C++中关于标准输出流cout中使用递增运算符的问题
- list_entry(ptr, type, member)
- 1038. 统计同成绩学生(20)
- C++高精度
- 小小君的C语言第十一课
- 小小君的C语言第十课
- C语言中运算符的结合性
- C++标识符override(覆盖),final(禁止),隐藏
- 用C语言导入mysql库
- C语言注册登录系统
- C++ assert
- 1015. 德才论 (25)
- C++之编码问题(Unicode,ASCII,本地默认)
- c语言中的字符数组和字符串之间的关系
- 用哈弗曼树编码字符串 求出编码后字符串二进制位长度
- c语言学习之基础知识点介绍(四):算术运算符和逗号表达式
- 2014 蓝桥杯 预赛 c/c++ 本科B组 第四题:史丰收速算(7' )
- 【C语言】 棋盘游戏