【发布时间】:2012-11-29 13:08:41
【问题描述】:
我正在关注 C++ 教程,并查看字符串并使用 +=、==、!= 等运算符重载。目前我有一个简单的 if 语句:
if(s1 < s2)
cout << s2 <<endl;
else
if(s2 < s1)
cout << s1 << endl;
else
cout << "Equal\n";
但这是如何工作的,程序如何确定哪个字符串大于另一个字符串? 环顾四周,我发现了一个基本的模板声明:
template<class charT, class traits, class Allocator>
bool operator< ( const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs );
这是否定义了< 的工作方式?如果是这样,<charT,traits,Allocator> 是什么意思/做什么?
以下运算符对字符串也有任何意义吗? -= 和 *=
【问题讨论】:
-
由于
std::string实际上是typedef的std::basic_string<char, std::char_traits<char>, std::allocator<char>>,因此该函数模板的一个特定实例是bool std::operator<(const std::string&, const std::string&);,它可能由您的s1 < s2和s2 < s1表达式调用。
标签: c++ operator-overloading string-comparison stdstring