【问题标题】:Comparing std::string and C-style string literals比较 std::string 和 C 风格的字符串文字
【发布时间】:2020-04-16 19:50:36
【问题描述】:

假设我有以下代码:

#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 风格的字符串 文字。

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

【问题讨论】:

  • basic_string/operator_cmp(在你的情况下是(7))。
  • Fwiw,只要一种类型可以转换成另一种,一般都可以比较。您可以从 c 字符串初始化 std::string

标签: c++ comparison c-strings stdstring c++-standard-library


【解决方案1】:

是因为下面compare operator defined for std::string

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

这允许在std::stringconst char* 之间进行比较。如此神奇!


窃取 @Pete Becker 的评论:

"为了完整起见,如果此重载不存在,则比较 仍然可以工作;编译器将构造一个临时对象 从 C 风格的字符串 中键入 std::string 并比较两者 std::string 对象,使用the first overload of 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)

这就是为什么这个操作符(即 overload 7)存在的原因:它消除了 对该临时对象的需求以及涉及的开销 创建和销毁它。”

【讨论】:

  • 并且,为了完整起见,如果不存在此重载,则比较仍然有效;编译器将构造一个std::string from the C-style string and compare the two std::string 对象类型的临时对象。这就是该运算符存在的原因:它消除了对临时对象的需求以及创建和销毁它所涉及的开销。
  • @PeteBecker 当然,我已将其添加到答案中。谢谢指出!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 2016-05-08
  • 1970-01-01
  • 2014-07-15
  • 2017-08-28
  • 2012-06-13
  • 2015-02-11
相关资源
最近更新 更多