简体   繁体   中英

How does the const char* and string comparison work in C++?

Consider the following code snippet:

#include <iostream>
int main() {
    std::string str = "Hello";
    const char *cstr = "Hello";
    if (cstr == str) {
        std::cout<<"Both are same string.";
    }
    return 0;
}

I am having difficulty guessing how the const char* and string comparison work:

if (cstr == str) {

As per my understanding, the overloaded operator of the left operand ( cstr in this case) is called with str as the argument. Now there is no overloading of == for const char*. So how does the above comparison even work?

Had the comparison been str==cstr , I would have no issues accepting it (as == for std::string is overloaded and it accepts const char* as an argument for comparison).

Note:- I am using gcc-4.8.1 for compiling the above code.

From http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp .

Compare a basic_string object and null-terminated array of T

template< class CharT, class traits, class Alloc >
bool operator==(const CharT* lhs, const basic_string<CharT,Traits,Alloc>& rhs);
template< class CharT, class traits, class Alloc >
bool operator==(const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs);

...

As per my understanding, the overloaded operator of the left operand (cstr in this case) is called with str as the argument. Now there is no overloading of == for const char*.

The operator is actually for std::string, and looks conceptually similar to this:

bool operator==(const char* const lhs, const std::string& rhs);

(though it reality it is templated).

This operator of std::string is added specifically for the operation you mention (comparing a std::string with a char*, when the char* is provided as the left-hand-side operand in the comparison).

Had the comparison been str==cstr, I would have no issues accepting it (as == for std::string is overloaded and it accepts const char* as an argument for comparison).

Both are present (specifically to support this situation).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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