《C++语言基础》程序阅读——运算符重载(一)
2015-04-21 16:52
295 查看
返回:贺老师课程教学链接
//(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 wl(2000,500,100),w2(5000,1000,300); cout<<(wl+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; }
相关文章推荐
- 第12周 《C++语言基础》程序阅读——多重继承(1)
- 《C++语言基础》程序阅读——多态性与抽象类
- 第8周项目1-程序阅读——运算符重载
- 《C++语言基础》程序阅读——学生信息管理系统
- 《C++语言基础》程序阅读——异常处理和命名空间
- 第九周 《C++语言基础》程序阅读——学生信息管理系统
- 第12周 《C++语言基础》程序阅读——多重继承(3)
- 第14周 《C++语言基础》程序阅读——标准输入输出对象及文本文件 (1)
- 《C++语言基础》程序阅读——字符串类的设计
- 《C++语言基础》程序阅读——二进制文件及文件的随机读写(4)
- 《C++语言基础》程序阅读——和对象找感觉
- 第12周 《C++语言基础》程序阅读——多重继承(4)
- 第九周 《C++语言基础》程序阅读——字符串类的设计
- 《C++语言基础》程序阅读——多重继承
- 第12周 《C++语言基础》程序阅读——多重继承(2)
- 《C++语言基础》程序阅读——指针、const、static(二)
- 《C++语言基础》程序阅读——继承和派生
- C++走向远洋——47(第十二周、运算符重载基础程序、阅读)
- 第八周项目零(1):阅读程序:运算符重载
- 第八周-运算符重载-课后实践·阅读程序