Overloading, I need help understanding

I don't know how to make the user choose which operation such as (+, -, *, / etc) he'd like to perform on the 2 objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;

class Square {
	
   private:
      double side;
     
      
   public:

      double getArea() {
         return side * side;
      }
		
      void setSide( double s ) {
         side = s;
      }

     
     
		
      // Overload + operator to add two Square objects.
      Square operator+(const Square& b) {
         Square square;
         square.side = side + b.side;
         return square;
      }
		
    };

// Main function
int main( ) {
   Square Square1;                
   Square Square2;                
   Square Square3; 
   
   double area = 0.0;     
 
   
   Square1.setSide(2.0);
   
   Square2.setSide(5.0);
 
   
   // Square1 area
   area = Square1.getArea();
   cout << "Area of Square1 : " << area <<endl;
 
   // Square2 area
   area = Square2.getArea();
   
   cout << "Area of Square2 : " << area <<endl;

   // Add two object as follows:
   Square3 = Square1 + Square2;

   // Area of Square3
   area = Square3.getArea();
   cout << "Area of Square3 : " << area <<endl;

   return 0;
}
Last edited on
Ask the user for the operator then use a switch statement:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
      char op;
  
    cout << "Enter the operator: ";
    cin >> op;
    switch (op)
    {
    case '+':
        square3 = square1 + square2;
        break;
    case '-':
        square3 = square1 - square2;
        break
    case '*':
        square3 = square1 * square2;
        break
    default:
        cout << "No a valid operator";
    }

Topic archived. No new replies allowed.