从命令行获取操作符并将其用作代码中的操作符

use*_*416 1 c++ math

我将从一个例子开始

me@blabla ./example + 3 5
Run Code Online (Sandbox Code Playgroud)

应该返回8.

我接受了参数,但我如何转换"+"

char* opp = argv[1];  
Run Code Online (Sandbox Code Playgroud)

到了

+ 
Run Code Online (Sandbox Code Playgroud)

在我的代码中使用?

因为我想使用相当多的运算符,有没有办法在不使用大的if语句的情况下执行此操作?

我希望那清楚,谢谢!

Jos*_*eld 5

您必须从char操作员那里获得某种映射.假设你已经有了35在一些整数变量xy,简单的解决方法是使用一个switch语句:

switch (opp[0]) {
  case '+': result = x + y; break;
  case '-': result = x - y; break;
  // and so on...
}
Run Code Online (Sandbox Code Playgroud)

或者,你可以有一个std::mapchars到std::function<int(const int&,const int&)>:

typedef std::function<int(const int&,const int&)> ArithmeticOperator;
std::map<char, ArithmeticOperator> ops =
  {{'+', std::plus<int>()},
   {'-', std::minus<int>()},
   // and so on...
  };

int result = ops[opp[0]](x,y);
Run Code Online (Sandbox Code Playgroud)