2017-09-19 66 views
2

我正在编写一个样本C++程序来试验多态性和地图。 我有以下地图:C++ std :: map在“*”上失败?

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

每个类从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到主,发生崩溃(SegmentationFault)。
如果我编辑代码并通过1 x 1它工作正常。

有什么我失踪的std::map?也许有关*被用作通配符或什么?

+0

查找术语“内存泄漏”,然后从不使用'new'一次。 – nwp

+6

'*'是大量shell中的特殊字符,基本上扩展为当前目录下的所有文件,尝试通过'1 \ * 1'。 – Holt

+0

@nwp如果我应该清理它,这不是泄漏。在这里,我不是因为这是一个玩具程序而且一切都马上消失! – magicleon

回答

3

的问题是不是你的C++代码—即使它很酷利用unique_ptr,而不是原始指针—而是你的方法参数传递给你的程序,当你运行它来改善。

*字符在一个地段外壳的特殊含义,通常扩展到文件的当前目录列表,如:

$ 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 
+0

我现在专注于地图,我一定会考虑'unique_ptr'!谢谢! – magicleon