类和对象-2

四、实验结论

1. 实验内容 2

类的定义

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

类的实现

//graph.cpp

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() {
 int i;
 for(i=0;i<size;i++)
 {
  for(int j=size-i-1;j>=0;j--)
   cout<<" ";
  for(int j=0;j<=2*i;j++)
   cout<<symbol;
  cout<<endl;
 }
}

main函数

//main.cpp
#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; }

运行结果截图

运行环境为devc++

2.实验内容3

类的定义

//fraction.h
class fraction
{
    public:
        fraction();
        fraction(int x,int y);
        fraction(int x);
        void show();
        void add(fraction &b);//
        void min(fraction &b);//
        void mul(fraction &b);//
        void div(fraction &b);//
        void cmp(fraction &b,fraction &c);//比较 
    private:
        int top;
        int bottom;
};

类的实现

//fraction.cpp

#include<iostream>
#include"fraction.h"
using namespace std;

fraction::fraction()
{
 top=0;
 bottom=1;
}

fraction::fraction(int x,int y)
{
 top=x;
 bottom=y;
}

fraction::fraction(int x)
{
 top=x;
 bottom=1;
}

void fraction::show()
{
 cout<<top<<'/'<<bottom<<endl;
}

void fraction::add(fraction &b)

 fraction a;
 a.top=top*b.bottom+b.top*bottom;
 a.bottom=bottom*b.bottom;
 a.show();
}

void fraction::min(fraction &b)
{
 fraction a;
 a.top=top*b.bottom-b.top*bottom;
 a.bottom=bottom*b.bottom;
 a.show(); 
}
void fraction::mul(fraction &b)
{
 fraction a;
 a.top=top*b.top;
 a.bottom=bottom*b.bottom;
 a.show(); 
}
void fraction::div(fraction &b)
{
 fraction a;
 a.top=top*b.bottom;
 a.bottom=bottom*b.top; 
 a.show();
}
void fraction::cmp(fraction &b,fraction &c)
{
 double m,n;
 m=b.top/b.bottom;
 n=c.top/c.bottom;
 if(m<n)
 {
  cout <<b.top<<'/'<<b.bottom<<'<';c.show();cout<<endl;
 }
 else if(m==n)
 {
  cout <<b.top<<'/'<<b.bottom<<'=';c.show();cout<<endl;
 } 
 else
 {
  cout <<b.top<<'/'<<b.bottom<<'>';c.show();cout<<endl;
 }
}

main函数

//main.cpp

#include <iostream>
#include "fraction.h"
using namespace std;

int main()
{
 fraction a;
 fraction b(3,4);
 fraction c(5);
 a.show();
 b.show();
 c.show();
 c.add(b);
 c.min(b);
 c.mul(b);
 c.div(b);
 b.cmp(b,c);
 return 0;
}

运行结果截图

 

运行环境为devc++

五、实验总结与体会

把一个完整的关于类和对象的程序拆成几个部分做成项目,“类的实现”那个单元需要包含#include<iostream>这个头文件,以及“类的实现”和“main函数”的单元中都需要在头文件中包含进“类的定义"的那个单元。

除此以外,和上次的作业相比没有特别新的知识点。

猜你喜欢

转载自www.cnblogs.com/MINT510845604/p/8868029.html