Why doesn't the following invoke the overloaded operator == (const String &, const String &)? "cobblestone" == "stone"

Why doesn't the following invoke overloaded operator== (const String &, const String &) ?

 "cobble" == "stone" 
+4
source share
4 answers

Since in C ++ string literals are of type const char[] (also called a constant string with a zero end), and not std::string , not to mention String (whatever that is).
There is a built-in operator== comparing two char* by comparing their addresses. Since arrays are implicitly converted to pointers to their first elements (because you guessed it correctly, the C legacy), this statement comes in and compares the addresses of these literals in memory.

Assuming your String class has an implicit conversion constructor from const char* ( String::String(const char*) ), you can convert one of the two to String . Then the other line will be converted implicitly:

 String("cobble") == "stone" 

(If operator== overloads are not required for efficiency, they take String and a const char* values. If they are provided, they are included.)

+13
source

Since implicitly existing operator==(char*, char*) better for using == .

The == operator in the "cobble" == "stone" code can be mapped in different ways: operator==(char[], const String&) , operator==(const String&, String) , operator==(const String&, const std::string&) etc. provided that the conversion from the parameter type ( char* ) to the type of arguments ( String* , etc.). However, the usual char* comparison is best for input.

+6
source

Because these are simple sequences of characters, as in C, but not instances of the string class.

+5
source

"cobble" ist is interpreted as char* , and the compiler uses pointer comparison to compare char* . If you want to compare the contents of the strings, use

 std::string("cobble") == std::string("stone") 

and the compiler will use operator== (const std::string &, const std::string &) .

+1
source

Source: https://habr.com/ru/post/1307668/


All Articles