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::string从C风格的字符串和两个比较std::string对象,所使用的第一个重载operator==Run Code Online (Sandbox Code Playgroud)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)这就是这个运算符(即重载 7)存在的原因:它消除了对该临时对象的需求以及创建和销毁它所涉及的开销。”