如何将 char 符号“+”直接转换为操作 +(加法)? C++

How cast char symbol "+" directly to an operation + (addition) ? C++

问题来了,我有一个char符号:

char a = '+'; //- * % whatever arithmetic symbol 

我想要这样我就可以使用 a 的值作为操作。我不想使用 switch 来检查 a 是否为 '+',等等,然后为每个 case 写很多类似的行。我只需要根据 a:

的值更改操作
int b = 2a2; //b=4 if a = "+", b = 0 if a = "-" etc

但我不知道如何快速将 char 转换为操作。 C++ 有 stoi() 将字符串转换为整数,但如何将 char 转换为操作?

对了,+是什么类型的数据?在2+2这样的表达式中,2是一个整数,但是+是什么?是方法还是什么?

I want so that I could use the value of a as an operation.

抱歉,那根本不可能。好吧,无论如何都不是你编写它的方式(可能有一些低级的方法可以在运行时使用自修改代码来实现类似的东西,但这是我不会涉及的高级技术)。

I don't want to use a switch to check if a is '+', etc

这将是最简单的解决方案。好吧,我的意思是,它不需要是一个特定的 switch,而是 某个东西 ,它将 a 与所需的值进行比较,然后调用适当的代码匹配值。

I need just to change the operation, depending on the value of a.

我会为此使用 std::(unordered_)map,例如:

#include <unordered_map>
#include <functional>

const std::unordered_map<char, std::function<int(int, int)>> operations = {
    {'+', [](int a, int b){ return a + b; }},
    {'-', [](int a, int b){ return a - b; }},
    {'*', [](int a, int b){ return a * b; }},
    {'/', [](int a, int b){ return a / b; }},
    {'%', [](int a, int b){ return a % b; }},
    // etc...
};

char a = '+';
auto op = operations.at(a);
int b = op(2, 2); 

Demo

But I don't know how to cast the char to an operation quickly. C++ has stoi() to cast a string to an integer, but how to cast a char to an operation?

你不能,不是你想的那样。

By the way, which type of data is +? In an expression like 2+2, 2 is an integer, but what is +? Is it a method or what?

根本就不是一个类型。它是一个运算符。

我完全同意。您不能直接在 '-' 和运算符 - 之间进行转换。您需要以一种或另一种方式进行切换,正如另一个答案所暗示的那样,unordered_map 非常方便。

不过,对你的问题有不同的看法...

您基本上可以将自定义 classes 的实例与您喜欢的任何东西相互转换。例如,您可以编写一个 operation class 可以从 char:

构造
#include <iostream>

struct operation {
    enum type{ plus,minus};    
    type t;
    operation(char c){
        if (c == '+') t= plus;
        else if (c == '-') t = minus;
        else throw "unknown operator";
    }
    int operator()(int a,int b){
        if (t == plus) return a+b;
        else if (t == minus) return a-b;
        else throw "unknown operator";
    }
};

int main() {
    std::cout << operation('+')(3,1);
}

请注意 if-else 也可能是 switchswtichif-else 的长链更有效,但我个人更喜欢 if-else 用于少量选项。您想要避免的开关仍然存在。

现在当你有一个需要 operation 的函数时,你可以传递一个 '-' 并且该字符被隐式转换为 operation:

void foo(operation op){ }
foo('-');

对这一切持保留态度。我只关注“我想投”这方面,没有别的。特别是,我实际上不建议隐式转换,因为它们可能会造成混淆。有时他们恰到好处,这取决于您的决定,这并不总是那么容易。