2014-10-26 64 views
-5

如何使用数字参数创建操作方法(int op),以便通过操作(1)或操作(3)调用其他方法?我想我需要创建一个开关,但我不知道如何。C++中的调用方法

int subtraction(int n1, int n2) { //e.g. of simple method 
    return n1 - n2; 
} 

int multiplication (int n1, int n2){ 
    return n1*n2; 
} 

int operation(int op) { 
    // code that will call the method subtraction when I press 1. 
    // same for multiplication... 
} 

int main() { 
} 
+1

你问如何使用'if'语句? – 2014-10-26 14:49:33

+2

为什么不参加讲座并学习这些东西? – 2014-10-26 14:49:49

+0

我想他在问如何使用'switch'语句。 – Westbrook 2014-10-26 14:50:24

回答

1
int operation(int op, int n1, int n2) { 
    switch(op) 
    { 
     case 1: 
      return subtraction(n1, n2); 

     case 2: 
      return multiplication(n1, n2); 

     default: 
      // default case, when the op value is neither 1 or 2 
      cout << "Error! << endl; 
      return 0; 
    } 
} 

@Edit:增加了默认的情况下,以下建议。另外,我认为你应该让你的变量名称更具描述性。

+2

需要一个默认值,以防万一 – 2014-10-26 14:53:52

+0

我想这就是我要找的。但它给了我一个与返回乘法相符的错误(int n1,int n2); //类型名称是不允许的。在函数中调用的参数太少 – 2014-10-26 15:10:47

+1

默认值应返回值 – 2014-10-26 15:11:20