/*
*Copyright(c) 2016,烟台大学计算机学院
*作 者:刘金石
*完成日期:2016年5月11日
*问题描述:运算符重载阅读程序
*/
#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;
}
运行结果:
运行分析;
程序中定义了Sample类,并把运算符重载写成友元函数,在函数参数列表中有两个参数
在主函数中,obj3=obj1+obj2调用了运算符重载函数,并把结果赋给obj3,所以结果输出30
程序二:
#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;
}
运行结果:
x=40
运行分析;
程序中定义了Sample类,运算符重载为成员函数,在主函数中,
obj3=obj1+obj2调用了运算符重载函数,并把结果赋给obj3,所以结果输出40
其实obj3=obj1+obj2相当于obj3=obj1.operator+(obj2);
#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;
}
运行结果:8100
运行分析:
程序中定义了Wages类,成员函数中有运算符重载函数,
主函数中有wl+w2也可写w1.operator+(w2)调用运算符重载函数
程序三:
#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;
}
运行结果:0101
程序分析:
程序中定义了">"的运算符重载函数,
对于p1>p2,3!=4,所以返回m>p.m,为假,输出0
对于p2>p1,4!=3,所以返回m>p.m,为真,输出1
对于p2>p3,4==4,返回n>n.p,为假,输出0
对于p3>p2,4==4,返回n>n.p,为真,输出1