我可以使用!=和C ++ ==为字符串比较不写我自己? [英] Can I use != and == in C++ for string comparison without writing my own?

查看:191
本文介绍了我可以使用!=和C ++ ==为字符串比较不写我自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么在换句话说字符串比较C和C ++之间的区别?

我是从'C'阵营。我看到程序中使用==比较字符串,我试图找到它的过载程序,但是没有找到。这是否意味着C ++处理字符串(的char [])自然地==和!=?结果
如果我有我自己定义的String类,这将是相同的,我可以使用==和!=没有定义呢?或者它仅适用于的char []?搜索结果
编辑:结果
它看起来像我C混合的的char []与C ++ std :: string类。 OK,这个老问题仍然适用。一些随后的问题如下:结果
我的程序定义的char []变量,但与==操作符进行比较。这似乎工作。他们是C风格的字符串,但一起工作==。难道编译器自动将其转换为为std :: string对我来说,这样的程序工作?_爱
EDIT2:结果
这里是一个工作的样本。结果

 如果(名称==)的回报;

,其中名是一类MyString的项目。它有一个参数的char *一个construtor。结果
MyString的具有公共职能的数据(),它返回的char * C风格的字符串指针。结果
所以,我是比较MyString的对象?或C风格的字符串?结果
无过载!=我自己,我可以做类似下面?

 如果(name.data()!= somes_ [I]。数据())
....


解决方案

这是否意味着C ++处理字符串(的char [] )使用<$自然C $ C> == 和!=

即可。这是不对的<$比较相互之间的C风格的字符串(即的char [] 的char * ) C $ C> == 或!= (以C和C ++),因为你最终会比较指针,而不是字符串。

在C ++中,可以比较 STD ::字符串 与C风格的字符串或其它的 的std ::字符串 因为的std ::字符串的对象的 运算符== 运算符!=

 的std ::字符串STR1(ABC),STR2(DEF);
如果(STR1 = STR2&安培;!&安培; STR1 ==ABC)
    性病::法院LT&;&LT; 是的,我知道了。

What's difference between C and C++ in string comparison in other words?

I came from 'C' camp. I saw program using == to compare strings, I tried to find its overloading program, but did not find one. Does it mean C++ deal with string (char []) naturally with == and !=?
If I have my own defined String class, would it be same that I can use == and != without defining them? or it applies only to char []?

Edit:
It looks like I mixed C's char[] with C++ std::string class. OK, the old question still apply. Some followed questions as below:
My programs defined char[] variables, but compared with "==" operator. It seemed work. They are C-style string, but work with "==". Did compiler auto-convert them to std::string for me so that the programs worked?

Edit2:
Here is a working sample.

if(name == "") return;

where "name" is a MyString class item. It has a construtor with a parameter char*.
MyString has a public function data(), it returns char* C-style string pointer.
So, am I comparing MyString objects? or C-style strings?
Without overload "!=" myself, can I do something like below?

if( name.data() != somes_[i].data() )
....

解决方案

"Does it mean C++ deal with string (char []) naturally with == and !=?"

No. It is wrong to compare C-style strings (i.e. char[] or char*) between each other with == or != (in both C and C++), because you will end up comparing pointers rather than strings.

In C++ it is possible to compare std::string object with a C-style string or another std::string object because of the std::string's operator== and operator!=:

std::string str1("abc"), str2("def");
if (str1 != str2 && str1 == "abc")
    std::cout << "Yep, I got it.";

这篇关于我可以使用!=和C ++ ==为字符串比较不写我自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆