一.实验结论:
1.项目1:(1)类的声明
#ifndef GRAPH_H #define GRAPH_H // 类Graph的声明 class Graph { public: Graph(char ch, int n); // 带有参数的构造函数 void draw(); // 绘制图形 private: char symbol; int size; }; #endif
(2)类的实现
// 类graph的实现 #include "graph.h" #include <iostream> using namespace std; // 带参数的构造函数的实现 Graph::Graph(char ch, int n): symbol(ch), size(n) { symbol=ch; size=n; } // 成员函数draw()的实现 // 功能:绘制size行,显示字符为symbol的指定图形样式 // size和symbol是类Graph的私有成员数据 void Graph::draw() { int i,j; for(i=0;i<size;i++) { for(j=1;j<=2*size-1;j++) { if(j>=size-i&&j<=size+i) { cout<<symbol; } else cout<<" "; } cout<<endl; } // 补足代码,实现「实验4.pdf」文档中展示的图形样式 }
(3)主函数
#include <iostream> #include "graph.h" using namespace std; int main() { Graph graph1('*',5), graph2('$',7) ; // 定义Graph类对象graph1, graph2 graph1.draw(); // 通过对象graph1调用公共接口draw()在屏幕上绘制图形 graph2.draw(); // 通过对象graph2调用公共接口draw()在屏幕上绘制图形 return 0; }
(4)实验结果
2.项目2:(1)类的声明
class Fraction { public: Fraction(int p=0,int q=1):top(p),bottom(q){};//重载函数 void plus(Fraction &a);//加 void minus(Fraction &a);//减 void multi(Fraction &a);//乘 void divi(Fraction &a);//除 void opera(int p,int q);//化简 void compare(Fraction &a);//比较 void output();//输出 private: int top; int bottom; };
(2)类的实现
#include"Fraction.h" #include<iostream> using namespace std; void Fraction::plus(Fraction &a) { top=a.top*bottom+a.bottom*top; bottom=a.bottom*bottom; opera(top,bottom);output(); } void Fraction::minus(Fraction &a) { top=a.top*bottom-a.bottom*top; bottom=a.bottom*bottom; opera(top,bottom);output(); } void Fraction::multi(Fraction &a) { top=a.top*top; bottom=a.bottom*bottom; opera(top,bottom);output(); } void Fraction::divi(Fraction &a) { top=a.top*bottom; bottom=a.bottom*top; opera(top,bottom);output(); } void Fraction::opera(int p,int q) { int i; for(i=p;i>0;i--) { if(p%i==0&&q%i==0) { break; } } if(q<0) { i=i*(-1); } top=top/i; bottom=bottom/i; } void Fraction::compare(Fraction &a) { int s=a.top*bottom-a.bottom*top; if(s>0) cout<<"a>b"<<endl; else if(s<0) cout<<"a<b"<<endl; else cout<<"a=b"<<endl; } void Fraction::output() { cout<<"The result is:"<<top<<"/"<<bottom<<endl; }
(3)主函数
#include"Fraction.h" #include <iostream> using namespace std; int main() { int x,y; Fraction a;a.output(); Fraction b(3,4);b.output(); Fraction c(5);c.output(); b.compare(c); cout<<"Please input the top and the bottom:"; cin>>x>>y; Fraction d(x,y);d.opera(x,y);d.output(); return 0; }
(4)实验结论
二.实验分析与讨论
这次实验难度比上次实验再高一等,实验练习1与项目1很轻松就做完了(共耗时8min),但是项目2却耗了我几天的时间。通过这次实验,我也发现了自己的一些不足:其一,构造函数的应用还是不太熟练,其二,对新知识的预习不太到位。在这两方面上,我以后会多加改进,练习。