第12周阅读程序(1)(2)(3)(4)
2016-05-11 16:50
176 查看
* *Copyright (c) 2016,烟台大学计算机学院 *All rights reserved. *文件名称 : *作 者 : 刘云 *完成日期 : 2016年5月11号 *版 本 号 : v6.0 * *问题描述 : 阅读程序(1)(2)(3)(4) *输入描述 : 无 *程序输出 : */ //(1) #include<iostream> using namespace std; class Sample { private: int x; public: Sample(){} Sample(int a){x=a;} void disp(){cout<<"x="<<x<<endl;} friend Sample operator+(Sample &s1,Sample &s2); }; Sample operator+(Sample &s1,Sample &s2) { return Sample(s1.x+s2.x); } int main() { Sample obj1(10); Sample obj2(20); Sample obj3; obj3=obj1+obj2; obj3.disp(); return 0; }
运行结果:
//(2) #include<iostream> using namespace std; class Sample { private: int x; public: Sample(){} Sample(int a){x=a;} void disp(){cout<<"x="<<x<<endl;} Sample operator+(Sample &s); }; Sample Sample::operator+(Sample &s) { return Sample(x+s.x); } int main() { Sample obj1(20); Sample obj2(20); Sample obj3; obj3=obj1+obj2; obj3.disp(); return 0; }
运行结果:
//(3)
#include<iostream>
using namespace std;
class Wages //“工资”类
{
double base;//基本工资
double bonus;//奖金
double tax; //税金
public:
Wages(double Cbase,double Cbonus,double Ctax):
base(Cbase),bonus(Cbonus),tax(Ctax){}
double getPay()const;//返回应付的工资
Wages operator+(Wages w)const;//重载加法
};
double Wages::getPay()const
{
return base+bonus-tax;
}
Wages Wages::operator+(Wages w)const
{
return Wages(base+w.base,bonus+w.bonus,tax+w.tax);
}
int main()
{
Wages w1(2000,500,100),w2(5000,1000,300);
cout<<(w1+w2).getPay()<<endl;
return 0;
}
运行结果:
//(4) #include<iostream> using namespace std; class Pair { int m; int n; public: Pair(int i,int j):m(i),n(j){} bool operator>(Pair p)const; }; bool Pair::operator>(Pair p)const { if(m!=p.m) return m>p.m; return n>p.n; } int main() { Pair p1(3,4),p2(4,3),p3(4,5); cout<<(p1>p2)<<(p2>p1)<<(p2>p3)<<(p3>p2); return 0; }
原因:
0 3!>4
1 4>3
0 4=4 3!>5
1 4=4 5>3
运行结果:
相关文章推荐
- saltstack之(四)远程执行及常用模块
- Highcharts 相关属性
- 继承Spring AbstractRoutingDataSource实现路由切换
- 安卓_高仿QQ
- 使用补偿算法对陀螺仪和电子罗盘进行数据融合,计算方位角
- 找工作笔试面试那些事儿(13)---操作系统常考知识点总结
- 接口测试的进展
- Fiddler 教程
- 针对Ajax常见错误的总结
- 数据结构实验之链表三:链表的逆置
- 学生信息管理系(二)
- 通过IL分析C#中的委托、事件、Func、Action、Predicate之间的区别与联系
- mysql命令行进入报错ERROR 2002 (HY000)
- Ubuntu16.04下 Matlab2015b安装与激活及注意事项:
- UDP广播通信
- 前端性能优化入门
- java中super的用法;
- poj 2533 N皇后问题 -- 递归回溯(打表)
- 单例
- 关于JavaScript的事件触发