/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:刘畅
* 完成日期:2015 年 4 月 24 日
* 版 本 号:v1.0
*
* 问题描述:阅读程序。
* 输入描述: ;
* 程序输出: 。
(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;
}
运行结果:
学习心得:
经过自己一个字母一个字母的敲出来,已经基本明白运算符重载是怎么一回事了。
前天还因为看到两个时间类的对象相减得到了一个整数不明白是怎么一回事,,,现在懂了。。。还是类中的数据成员进行计算得来的。