Need help with operators

Basically my question is how can I assign an operator, + - * /, to a variable and then use it within an equation using that variable? What I eventually want to do is generate a random number from 1-4 and have an operator assigned to the 1 2 3 4 index of an array and then have the operator plugged into the equation using the array.

Here is an example in code that obviously doesn't work.

Based on the code, the equation would be 6 + 2
Thanks for any help :)
1
2
3
4
5
6
7
8
9
10
11
12
13
  int main()
{
    int answer;
    string op[4];
    op[1] = "+";
    op[2] = "-";
    op[3] = "/";
    op[4] = "*";
    
    
    answer = 6 op[1] 2;
    //6 + 2
}


C++ has the concept of operator overloading, but to understand it, you must first understand the concept of classes and object oriented programming. In your case, you should rather write functions convering each operator role or use switch or both:
1
2
3
4
5
6
7
8
9
10
11
int add( int first, int second) {
    return first + second
};
char op;
switch(op)
{
    case '+':
        answer = add(6, 2);
    break;
    //etc
}

Last edited on
I can't think of any way to use the op strings unless you do a comparison of the operator, then branch to code that does the operation:

1
2
3
4
5
6
7
8

if( "+" == op[ 0 ] )
    answer = FirstNumber + SecondNumber;

if( "-" == op[ 1 ] )
    answer = FirstNumber - SecondNumber;



Also, op[ 4 ] is an invalid index: Arrays are zero-based (0 to array size - 1).
1
2
3
4
5
6
7
int add(int a, int b){return a+b;}
//etc...
int main()
{
   int(*func[4])(int,int) = {add, sub,...};
   return func[rand()%4](6,2);
}
Topic archived. No new replies allowed.