比较 std::string 和 C 风格的字符串文字
Comparing std::string and C-style string literals
假设我有以下代码:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std; // or std::
int main()
{
string s1{ "Apple" };
cout << boolalpha;
cout << (s1 == "Apple") << endl; //true
}
我的问题是:系统如何检查这两者? s1
是一个对象,而 "Apple"
是一个 C 风格的字符串 文字。
据我所知,不同的数据类型是不能比较的。我在这里错过了什么?
是因为下面的compare operator defined for std::string
template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); // Overload (7)
这允许在 std::string
和 const char*
之间进行比较。这就是魔法!
窃取 @Pete Becker 的评论:
"For completeness, if this overload did not exist, the comparison
would still work; The compiler would construct a temporary object of
type std::string
from the C-style string and compare the two
std::string
objects, using the first overload of
operator==
template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs,
const basic_string<CharT,Traits,Alloc>& rhs ); // Overload (1)
Which is why this operator(i.e. overload 7) is there: it eliminates
the need for that temporary object and the overhead involved in
creating and destroying it."
假设我有以下代码:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std; // or std::
int main()
{
string s1{ "Apple" };
cout << boolalpha;
cout << (s1 == "Apple") << endl; //true
}
我的问题是:系统如何检查这两者? s1
是一个对象,而 "Apple"
是一个 C 风格的字符串 文字。
据我所知,不同的数据类型是不能比较的。我在这里错过了什么?
是因为下面的compare operator defined for std::string
template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs ); // Overload (7)
这允许在 std::string
和 const char*
之间进行比较。这就是魔法!
窃取 @Pete Becker 的评论:
"For completeness, if this overload did not exist, the comparison would still work; The compiler would construct a temporary object of type
std::string
from the C-style string and compare the twostd::string
objects, using the first overload ofoperator==
template< class CharT, class Traits, class Alloc > bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const basic_string<CharT,Traits,Alloc>& rhs ); // Overload (1)
Which is why this operator(i.e. overload 7) is there: it eliminates the need for that temporary object and the overhead involved in creating and destroying it."