比较 std::string 和 C 风格的字符串文字

Adi*_*ash 9 c++ comparison c-strings stdstring c++-standard-library

假设我有以下代码:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std; // or std::

int main()
{
    string s1{ "Apple" };
    cout << boolalpha;
    cout << (s1 == "Apple") << endl; //true
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:系统如何在这两者之间进行检查?s1是一个对象,而"Apple"C 风格的字符串文字。

据我所知,不能比较不同的数据类型。我在这里缺少什么?

JeJ*_*eJo 16

这是因为定义了以下比较运算符std::string

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

这允许在std::string和之间进行比较const char*。因此魔法!


窃取@Pete Becker的评论:

“为了完整起见,如果过载不存在,比较仍然工作;编译器将构造类型的临时对象std::stringC风格的字符串和两个比较 std::string对象,所使用的第一个重载 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)
Run Code Online (Sandbox Code Playgroud)

这就是这个运算符(即重载 7)存在的原因:它消除了对该临时对象的需求以及创建和销毁它所涉及的开销。”

  • 而且,为了完整起见,如果这种重载不存在,比较仍然有效;编译器将从 C 风格字符串构造一个 `std::string 类型的临时对象,并比较两个 `std::string 对象。这就是这个运算符存在的原因:它消除了对该临时对象的需要以及创建和销毁它所涉及的开销。 (8认同)