Experiment 4 Classes and Objects - 2

graph.cpp
1  #ifndef GRAPH_H
 2  #define GRAPH_H
 3  
4  // Declaration of class Graph 
5  class Graph 
 6  {
 7      public :
 8          Graph( char ch, int n);    // Constructor with parameters 
9          void draw();      // draw graphics 
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 ) ;   // Define the Graph class Object graph1, graph2 
6      graph1.draw(); // Call the public interface draw() through the object graph1 to draw the graph on the screen 
7      graph2.draw(); // Call the public interface draw() through the object graph2 to draw the graph on the screen 
8      return  0 ; 
 9 }
main.cpp

Operating environment: Dev C++

Run the screenshot:

Algorithm idea: output in separate lines, calculate the number of leading spaces and the number of characters output, and output in sequence.

 

 

fraction.cpp
class Fraction
{
    private :
         int top,bottem;        // numerator, denominator     
    public :
        Fraction(int a=0,int b=1) : top(a) , bottem (b) {check();};
        Fraction(Fraction &f) : top(f.top) , bottem (f.bottem) {check();};               // copy constructor 
        void show();
         void compare(Fraction & f);
         void add(Fraction &f) ;                  // add 
        void subtract(Fraction &f);             // subtract 
        void multiply(Fraction &f);             // multiply 
        void divide(Fraction &f);               // divide 
        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

Operating environment: Dev C++

Run the screenshot:

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

 

 

 

Summary: Classes and objects correspond all things in reality to objects, making object-oriented programming possible. Moreover, the security attributes of some data can also be taken into account.

           In this assignment, I started to write some practical programs (such as finding the least common multiple, etc.) into a file, which can be directly extracted or called later when needed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324689201&siteId=291194637