簡體   English   中英

比較 std::string 和 C 風格的字符串文字

[英]Comparing std::string and C-style string literals

假設我有以下代碼:

#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::stringconst char*之間進行比較。 因此魔法!


竊取@Pete Becker的評論:

“為完整起見,如果此重載不存在,則比較仍然有效;編譯器將從C 樣式字符串構造一個std::string類型的臨時對象,並使用第一個重載比較兩個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 )存在的原因:它消除了對該臨時對象的需求以及創建和銷毀它所涉及的開銷。”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM