gpt4 book ai didi

c++ - 比较 std::string 和 C 样式字符串文字

转载 作者:行者123 更新时间:2023-12-02 04:59:23 25 4
gpt4 key购买 nike

假设我有以下代码:

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

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

最佳答案

是因为以下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 的评论:

"For completeness, if this overload did not exist, the comparison would still work; The compiler would construct a temporary object of type std::string from the C-style string and compare the two std::string objects, using 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)

Which is why this operator(i.e. overload 7) is there: it eliminates the need for that temporary object and the overhead involved in creating and destroying it."

关于c++ - 比较 std::string 和 C 样式字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com