阅读程序
/*
*copyright (c)2015,烟台大学计算机学院
*All rights reserved
*文件名称:project.cpp
*作者:孙春红
*完成日期:2015年4月23日
*版本号:v1.0
*
*问题描述:阅读程序。
*输入描述:略。
*程序输出:略。
*/
运算符重载是指对一个运算符的一名多用,实际是函数重载。重载运算符的函数的一般格式是:函数类型 operator 运算符名称(形参表)
(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;
}
答案:
x=2
知识点总结:
学会使用简单的运算符重载的方法。
//(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); //this->x+s.x;
}
int main()
{
Sample obj1(20);
Sample obj2(20);
Sample obj3;
obj3=obj1+obj2;//相当于c3=c1.operator+(c2);
obj3.disp();
return 0;
}
答案:
x=40
//(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;
}
答案:
8100
//(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) //this->m!=p.m
return m>p.m; //如果成立,返回1,不成立返回0;
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