std::string somestring;
/*...*/
if("STRING_LITERAL" == somestring)
std::cout << "Strings are Equal" << std::endl;
In the sampl开发者_运维问答e code above, how does a C++ compiler interpret the ==
operator? As the ==
operator overloaded by the string class?
If you're using std::string
then you should have #include
d the <string>
header. Assuming this is the case then the operator==
selected should be the non-member template function from <string>
with appropriate template parameters deduced. (ISO/IEC 14882:2003 21.3.7.2 [lib.string::operator==])
template<class charT, class traits, class Allocator>
bool operator==(const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
The std::string
class (strictly class template specialization) doesn't contain any member overloads for operator==
.
Yes. The operator==
is implemented as a free standing function, that's why the positioning is irrelevant. It could be
bool operator==(const string& str1, const char* str2){
// ...
}
or
bool operator==(const char* str1, const string& str2){
// ...
}
or even a simple
bool operator==(const string& str1, const string& str2){
// ...
}
With an automatic conversion from char const*
to string
, as the relevant constructor of std::string
is non-explicit.
There is an overload of operator==
that does the right thing:
template <class charT, class traits, class Allocator>
bool operator==(const charT* lhs,
const basic_string<charT, traits, Allocator>& rhs);
You can find it in 21.3 §1 of the C++0x FDIS on page 635.
From http://www.cplusplus.com/reference/string/operators/ , these overloads are defined:
bool operator== ( const string& lhs, const string& rhs );
bool operator== ( const char* lhs, const string& rhs );
bool operator== ( const string& lhs, const char* rhs );
Note that these are global functions, not methods of the string
class (but they'll be implemented using string::compare()
.
精彩评论