实验 4 类和对象-2

graph.cpp
 1 #ifndef GRAPH_H
 2 #define GRAPH_H
 3 
 4 // 类Graph的声明 
 5 class Graph 
 6 {
 7     public:
 8         Graph(char ch, int n);   // 带有参数的构造函数 
 9         void draw();     // 绘制图形 
10     private:
11         char symbol;
12         int size;
13 };
14 
15 
16 #endif
graph.h
1 #include <iostream>
2 #include "graph.h"
3 using namespace std;
4 int main() {
5     Graph graph1('*',5), graph2('$',7) ;  // 定义Graph类对象graph1, graph2 
6     graph1.draw(); // 通过对象graph1调用公共接口draw()在屏幕上绘制图形 
7     graph2.draw(); // 通过对象graph2调用公共接口draw()在屏幕上绘制图形
8     return 0; 
9 } 
main.cpp

运行环境:Dev C++

运行截图:

算法思路:分行输出,计算前导空格个数、字符输出次数,依次输出即可。

 

 

fraction.cpp
class Fraction
{
    private:
        int top,bottem;       //分子,分母    
    public:
        Fraction(int a=0,int b=1) : top(a) , bottem (b) {check();};
        Fraction(Fraction &f) : top(f.top) , bottem (f.bottem) {check();};              //复制构造函数 
        void show();
        void compare(Fraction &f);
        void add(Fraction &f);                 //
        void subtract(Fraction &f);            //
        void multiply(Fraction &f);            //
        void divide(Fraction &f);              //
        void check();
};
fraction.h
#include <iostream>
#include "fraction.h"
using namespace std;

int main(int argc, char** argv) {
    Fraction f1;
    Fraction f2(-3,-12);
    Fraction f3(5);
    f1.show();
    f2.show();
    f3.show();
    f1.compare(f2);
    f2.compare(f3);
    Fraction f4(f1);
    f4.subtract(f3);
    f4.divide(f2);
    f4.show();
    
    return 0;
}
main.cpp

运行环境:Dev C++

运行截图:

Fraction

 - top : int

 - bottem : int

 + Fraction( a : int=0 , b : int=0 ) 

 + Fraction( f : Fraction & )

 + show() : void

 + compare( f : Fraction & ) : void

 + add( f : Fraction & ) : void

 + subtract( f : Fraction & ) : void

 + multiply( f : Fraction & ) : void

 + divide( f : Fraction & ) : void

 + check() : void

总结:类与对象将现实中的所有事物全部对应到对象中,使面向对象程序设计变成了可能。并且,还能兼顾到部分数据的安全属性。

           这次作业,我开始将一些实用性的程序(如求最小公倍数等)写进一个文件中,以后需要时可以直接提取或调用。

猜你喜欢

转载自www.cnblogs.com/rq1b-qsy666/p/8906173.html
今日推荐