C++ std::map 在“*”上失败?

C++ std::map failing on "*"?

我正在编写一个示例 C++ 程序来试验多态性和映射。 我有以下地图:

map<char,Operation*> ops;
ops['+'] = new Addition();
ops['-'] = new Subtraction();
ops['*'] = new Multiplication();
ops['/'] = new Division();

每个 class 继承自 Operation 并执行其名称建议的操作。

Everytrhing 工作正常,但是当我访问 ops['*'] 时程序崩溃了。如果我使用不同的 char,请这样说:

ops['x'] = new Multiplication();

程序有效。

整个main函数是这样的:

int main(int argc, char** argv){
    int x = atoi(argv[1]);
    char op = argv[2][0];
    int y = atoi(argv[3]);
    map<char,Operation*> ops;
    ops['+'] = new Addition();
    ops['-'] = new Subtraction();
    ops['*'] = new Multiplication();
    ops['/'] = new Division();
    cout<<ops[op]->op(x,y)<<endl;
}

我会重复我的问题:

如果我将 1 * 1 传递给 main,则会发生崩溃 (SegmentationFault)。
如果我编辑代码并传递 1 x 1 它工作正常。

std::map 有什么我遗漏的吗?也许与 * 用作通配符或其他东西有关?

问题不在于您的 C++ 代码 — 即使通过使用 unique_ptr 而不是原始指针可以很好地改进它 — 但问题在于您在 运行 时向程序传递参数的方式。

* 字符在许多 shell 中具有特殊含义,通常扩展为当前目录中的文件列表,例如:

$ ls
main.cpp main
$ echo 1 * 1
1 main.cpp main 1

您需要使用反斜杠转义它 \ 或在调用您的程序时在引号内传递它:

$ echo 1 \* 1
1 * 1
$ echo 1 "*" 1

我建议使用反斜杠版本,因为有些 shell 甚至可以在标准引号内扩展 *

在你的例子中,如果你的程序被称为 main,你会这样做:

$ ./main 1 \* 1 ex