比较std::string和C风格字符串字面值

9
假设我有以下代码:
#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 风格字符串文本。
据我所知,不同的数据类型不能进行比较。我在这里错过了什么吗?

6
在这种情况下,您需要查看的是basic_string类的比较运算符。您可以在此页面中找到有关该类运算符的详细信息,包括operator==operator!=operator<等。注意,数字7代表C++11标准所使用的版本,也可能会有其他版本可用。 - Jarod42
2
就算一个类型可以转换成另一个类型,你通常也可以进行比较。你可以从 c-string 初始化一个 std::string - NathanOliver
1个回答

16

正是因为下面这个std::string定义的比较运算符, 才会出现这种情况。

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

这允许比较std::stringconst 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."


8
为了完整性,即使没有这个重载,比较仍然可以工作;编译器将构造一个临时的std::string对象从C风格字符串中,再比较这两个std::string对象。这就是为什么有这个运算符:它消除了临时对象的需要以及创建和销毁它所涉及的开销。 - Pete Becker
1
@PeteBecker 当然,我已经将它添加到答案中。感谢您指出! - JeJo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接