假设我有以下代码:
#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] 删除。
我来说两句