简体   繁体   English

比较字符串对象与C ++中的字符串文字:为什么没有编译错误?

[英]comparing string object with string literal in C++: why no compile errors?

I wrote some code like this: 我写了一些这样的代码:

#include<string>  
using namespace std;  
int main() {  
    string str;
    ...
    if(str=="test")    //valid????
        //do something
    ...
    return 0;
}

After re-reading the code later I was curious that how did the compiler give no errors? 稍后重新阅读代码后,我很好奇编译器没有给出任何错误?
Note: I already checked the reference and it looks like there should be some sort of type mismatch error (comparing string object with array of char) 注意:我已经检查了引用,并且看起来应该存在某种类型的不匹配错误(将字符串对象与char数组进行比较)

edit: sorry for the = to == typo error. 编辑:对不起= = =拼写错误。 it is already fixed 它已经固定

edit 2: issues: 编辑2:问题:

  • there aren't any of operator==(string,char*) or operator==(string,char[]) or similar operators defined in the reference(cppreference.com) 参考(cppreference.com)中没有定义任何operator ==(string,char *)或operator ==(string,char [])或类似运算符
  • no conversion operator from char* or char[] to string 从char *或char []到字符串没有转换运算符

As others have mentioned, the single = sign performs assignment, not comparison. 正如其他人提到的那样,单个=符号执行赋值,而不是比较。

But the comparison operator is defined, like assignment, by operator overloading , one of the most essential features of C++. 但是比较运算符就像赋值一样是由运算符重载定义的, 运算符重载是C ++的最基本功能之一。

The expression str = "test" is transformed into a function call str.operator= ("test") , and the expression str == "test" would be transformed into either str.operator== ("test") , or operator==(str,"test") , whichever one works. 表达式str = "test"转换为函数调用str.operator= ("test") ,表达式str == "test"将转换为str.operator== ("test")operator==(str,"test") ,无论哪个可行。

Even if the overload function weren't defined for operands of std::string and char * , the compiler would still try to find function(s) to convert the arguments to types that did match such a function. 即使未为std::stringchar *操作数定义重载函数,编译器仍会尝试查找函数以将参数转换为与该函数匹配的类型。

EDIT: Hah, std::string cannot be converted to bool so the if condition would still be an error. 编辑:啊, std::string无法转换为bool因此if条件仍然是错误。 I assume this is an artifact of making a nice snippet for the question. 我认为这是为问题制作一个不错的摘录的产物。

if(str="test")  //it's an assignment not a comparison.

change it to if(str=="test") 将其更改为if(str=="test")

 why no compile errors?

Because it's c++ not c. 因为它是c ++而不是c。 std::string has defined this == operator . std::string定义了此==运算符。

if(str="test")  //it's an error: because you can't convert string to boolean type. 
                  which is expected as condition.

error like :could not convert 's.std::basic_string<_CharT, _Traits, _Alloc>::operator=
<char, std::char_traits<char>, std::allocator<char> >(((const char*)"p"))' from 
'std::basic_string<char>' to 'bool' 

If you do this 如果你这样做

if(str="test"){}

you assign "test" to str . 您将“ test”分配给str As this is a valid operation, the assignment will return &str a reference to your object, so your if-condition will always be fulfilled. 由于这是有效操作,因此赋值将返回&str对您的对象的引用,因此您的if条件将始终得到满足。 Of course, if str == 0 then it will give an error. 当然,如果str == 0 ,则将给出错误。 So better do: 所以最好做:

if(str == "test"){}

Thanks to James Kanze! 感谢James Kanze!

As mentioned, it isn't compilation error due the operator overloading (ignoring the fact that you're not comparing but assigning). 如前所述,这不是由于运算符重载而引起的编译错误(忽略您不是在进行比较而是在分配的事实)。 If you use any object without this operator then, yes, it will be a compilation error: 如果使用不带该运算符的任何对象,则是的,这将是编译错误:

// Foo does not have comparision operator
struct Foo {};

// Bar have comparision operator
struct Bar
{
    // Next line is the operator overload.
    bool operator ==(const char *pstr) const { return true; };
};

// string have comparision operator
std::string Test("test");

if (Foo == "test")  // compilation error
if (Bar == "test")  // uses the Bar::operator ==
if (Test == "test") // uses the basic_string<char>::operator ==
{ /* do something */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM