C++实验报告.doc
文本预览下载声明
深 圳 大 学 实 验 报 告
课程名称: 面对对象程序设计
实验项目名称: 类和对象以及运算符重载
学院: 信息工程学院
专业: 电子信息工程
指导教师:
报告人: 学号:2009130172 班级: 电子2班
实验时间: 2011.12.05
实验报告提交时间:
教务部制
实验目的与要求:
编程:建立一个分数类。分数类的数据成员包括分子和分母,操作包括约分、通分、加、乘、显示和输入。
将实验12范例1加、减重载为成员函数。 方法、步骤:
实验过程及内容:(1)建立分数类
#include iostream
#include cmath
using namespace std;
class fraction {
int above;
int below;
void reduction();
void makeCommond (fraction);
public:
fraction (int a=0,int b=1){
above=a;
below=b;
}
fraction add(fraction);
fraction sub(fraction);
fraction mul(fraction);
fraction div(fraction);
fraction reciprocal();
bool epual(fraction);
bool greatThan(fraction);
bool lessThan(fraction);
void display();
void input();
};
void fraction :: reduction() {
int i,a,b;
if (below0) {
above=-above;
below=-below;
}
a=abs(above);
b=abs(below);
while(a%b) {
i=a;
a=b;
b=i%b;
}
above/=b;
below/=b;
}
void fraction :: makeCommond (fraction b) {
int temp;
reduction();
b,reduction();
above*=b.below;
b.above*=below;
temp=below*b.below;
below=b.below=temp;
}
fraction fraction :: add(fraction b) {
fraction temp;
makeCommond(b);
temp.above=above+b.above;
temp.below=below;
temp.reduction();
return temp;
}
fraction fraction :: mul(fraction b) {
fraction temp;
temp.above=above*b.above;
temp.below=below*b.below;
temp.reduction();
return temp;
}
void fraction :: display() {
reduction ();
cout约分后分子是:above\t约分后分母是:belowendl;
}
void main () {
fraction f1(-4,-6),f2(-4,6),f3(4,-6),f4(3,4),f5;
coutf1;f1.display();
coutf2;f2.display();
coutf3;f3.display();
coutf4;f4.display();
f5=f1.add(f4);
coutf1+f4=f5;f5.display();
f5=f2.add(f4);
coutf2+f4=f5;f5.display()
显示全部