实验四

实验四

项目一:

源码:

类的定义:

#ifndef GRAPH_H
#define GRAPH_H

// 类Graph的声明 
class Graph {
	public:
		Graph(char ch, int n);   // 带有参数的构造函数 
		void draw(); 	// 绘制图形 
	private:
		char symbol;
		int size;
};


#endif

类的实现

// 类graph的实现
 
#include "graph.h" 
#include <iostream>
using namespace std;

// 带参数的构造函数的实现 
Graph::Graph(char ch, int n): symbol(ch), size(n) {
}


// 成员函数draw()的实现
// 功能:绘制size行,显示字符为symbol的指定图形样式 
//       size和symbol是类Graph的私有成员数据 
void Graph::draw() {
	for(int i=1;i<=size;i++)
	{
		for(int k=size-i;k>=0;k--)
		{
			cout<<" ";
		}
		for(int j=0;j<2*i-1;j++)
		{
			if(j<2*i-2)
				cout<<symbol;
			if(j==2*i-2)
				cout<<symbol<<endl;
		}
	}
	// 补足代码,实现「实验4.pdf」文档中展示的图形样式 
}


主函数

#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; 
} 

运行结果

这里写图片描述

项目二:

源码:

类的定义

class Fraction{
	public:
		Fraction(int a=0,int b=1 ):top(a),bottom(b){}//构造函数 
		Fraction operator+(const Fraction &a);
		Fraction operator-(const Fraction &b);
		Fraction operator*(const Fraction &c);		
		Fraction operator/(const Fraction &d);//运算符重载函数; 
		void output();	//输出函数 
		void compare(Fraction &a);//比较函数;	
	private:
		int top;//分子; 
		int bottom;//分母; 
};

类的实现

#include"Fraction.h"
#include<iostream>string gon()
#include<cmath>
using namespace std;
Fraction Fraction::operator+(const Fraction &a){
	return Fraction(top*a.bottom+a.top*bottom,a.bottom*bottom);
}
Fraction Fraction::operator-(const Fraction &b){
	return Fraction(top*b.bottom-b.top*bottom,bottom*b.bottom);
}
Fraction Fraction::operator*(const Fraction &c){
	return Fraction(top*c.top,bottom*c.bottom);	 
}
Fraction Fraction::operator/(const Fraction &d){
	return Fraction(top*d.bottom,bottom*d.top);
}

void Fraction::output(){
	int t,x,y;
	if(abs(top)>abs(bottom))
		t=abs(bottom);
	else
		t=abs(top);
	for(int i=1;i<t;i++){
		if(top%i==0&&bottom%i==0){
			top/=i;
			bottom/=i;
			i=1;
		}
	}
	if(bottom<0){
		top*=-1;
		bottom*=-1;
	}
	cout<<top<<"/"<<bottom<<endl; 
}

主函数

#include"Fraction.h"
#include<iostream>
using namespace std;
int main(){
	Fraction a(1,-6);
	Fraction b(4,-6);
	Fraction c;
	c=a+b;
	c.output();
	c=a*b;
	c.output(); 
	c=a/b;
	c.output();
	c=a-b;
	c.output();
	return 0;
}

运行结果

这里写图片描述

实验感想

对这种方法还要勤加练习,才能更好地掌握!在项目二中的比较函数不知怎么写,望评论的人能指点一二!

posted @ 2018-04-22 18:09  obamax  阅读(98)  评论(0编辑  收藏  举报