簡體   English   中英

為什么const char *強制轉換為std :: string有效?

[英]Why does a const char* cast to std::string work?

這個演員讓我困惑:

#include <string>
#include <iostream>
#include <memory>

using namespace std;

int main() {
    string str1 =  (string)"I cast this thing" +  " -- then add this";
    cout << str1 << endl;
}

有人可以解釋為什么這個c樣式轉換為字符串工作(或被允許)? 我將生成的優化程序集與以下內容進行了比較

string str1 =  string("I construct this thing") +  " -- then add this";

它們似乎是相同的,所以我覺得我忘記了一些c ++語義,它實際上允許這種類型的轉換/構造互換。

 std::string str2 =  std::string("I construct this thing") +  " -- then add this";

是的,如果你有一個構造函數接受一個像這樣的參數,它將用於將參數類型轉換為對象類型。 這就是為什么我們可以將const char*傳遞給帶字符串的函數。

轉換構造函數

C風格的演員陣容將進行常規演員和靜態演員或重新演繹演員。

如果已定義,靜態強制轉換將使用用戶定義的轉換。

std::string有一個構造函數string(const char *)

語法std::string("something")static_cast<std::string>("something")(std::string)"something"是等價的。 它們都將使用std::string::string(const char *)構造std::string::string(const char *)構造一個臨時的std::string 語法之間的唯一區別是在轉換指針時。

std::string有一個構造函數的形式

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

這充當轉換運算符。 如果將字符串文字強制轉換為std::string ,它將調用此構造函數並創建臨時的std::string

暫無
暫無

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

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