比较std :: string和C样式的字符串文字

阿迪亚·普拉卡什(Aditya prakash)

假设我有以下代码:

#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样式的字符串文字。

据我所知,无法比较不同的数据类型。我在这里想念什么?

杰乔

这是因为为以下定义了比较运算符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的评论:

“为完整起见,如果不存在此重载,则比较仍将起作用;编译器将std::string使用C样式字符串构造一个临时类型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)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章