Passing enum to a struct

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  enum class Operation {
      
    Add,
    Subtract,
    Multiply,
    Divide
};

struct Calculator (Operation){
    

};


int main(){
    

};



The task:
2-1. Create an enum class Operation that has values Add, Subtract, Multiply, and Divide.
2-2. Create a struct Calculator. It should have a single constructor that takes an Operation.
2-3. Create a method on Calculator called int calculate (int a, int b).
Upon invocation, this method should perform addition, subtraction, multiplication, or division based on its constructor argument and return the result.


In the task at hand I am meant to "develop" a simple type of calculator that has enum class for all of the functions of the calculator. I have immense trouble on understanding how the points 2-2 and 2-3 are supposed to work, and in the book we've gone through switch-cases so I suppose they need to be used. I assume that my version of the 2-2 is close on how its supposed to be; A calculator struct that has a constructor that's taking an Operation (this though gives me a "Variable has incomplete type 'struct Calculator'" error). On 2-3 I have no idea on how/where I could implement a method in the class so it could accept more parameters. One way that I have thought that the calculator class should be:

 
struct Calculator (int a, int b, Operation)


This way I could pass all three parameters in and pick which operation I want to do with the calculator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct calc
{
   operation whatami;
   calc(operation o){whatami = o;}
  int calculate(int a, int b) 
  {
     switch(whatami)... blah blah
  }
};

...
calc c(add);
int result = c.calculate(3,4);

you can make a function that does what you said, a,b and operation. the struct, constructor, and all are so you can learn to do things this way. this is a TERRIBLE object, so do not look for a "why the @#$% would I make something like this" ... its not obvious from this assignment and its hard to see until you have a bit more OOP studied. It boils down to one somewhat unusual use of OOP where an object is really little more than a function, (you would actually overload the () operator so c(3,4) would mean calculate(3,4) above) -- the struct brings some things in that a normal function can't do easily (sorta some of it via static variables, but it gets weird).

These are rare, in my experience, but when you need it, nothing else will do. Its called a functor.
Last edited on
Thank you so much for this!!!
Topic archived. No new replies allowed.