为什么在c ++中没有if(“Maya”==“Maya”)true? [英] Why isn't if ("Maya" == "Maya") true in c++?
本文介绍了为什么在c ++中没有if(“Maya”==“Maya”)true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我得到这个代码的结果是Maya不是Maya?
if(Maya ==Maya)
printf(Maya is Maya \\\
);
else
printf(Maya is not Maya \\\
);
解决方案
因为你实际上是比较两个指针。以下代替:
if(std :: string(Maya)==Maya){/ * ... * /}
/ pre>
if(std :: strcmp(Maya,Maya)== 0){/ * ... * /}
这是因为C ++ 03,§2.13.4说:
一个普通的字符串文字具有 n 类型的数组
$ b $ http://stackoverflow.com/questions/2985532/overloading-operator-to-compare-two-char-using-a-string-comparison\">此问题您为什么不能提供超载const char
==
对于这种情况。Any idea why I get "Maya is not Maya" as a result for this code?
if ("Maya" == "Maya") printf("Maya is Maya \n"); else printf("Maya is not Maya \n");
解决方案Because you are actually comparing two pointers - use e.g. one of the following instead:
if (std::string("Maya") == "Maya") { /* ... */ } if (std::strcmp("Maya", "Maya") == 0) { /* ... */ }
This is because C++03, §2.13.4 says:
An ordinary string literal has type "array of n
const char
"... and in your case a conversion to pointer applies.
See also this question on why you can't provide an overload for
==
for this case.这篇关于为什么在c ++中没有if(“Maya”==“Maya”)true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文