2015-04-12 173 views
1

我做了一些教程,並有這條線初始化字符串用雙引號

const std::string spaces(greeting.size(), " "); 

然而,沒有工作,直到我改變了雙引號爲單引號像

const std::string spaces(greeting.size(), ' '); 

是什麼關於字符串初始化中引號的問題?我試着檢查http://www.cplusplus.com/reference/string/string/,但沒有找到的東西,將這個給我解釋

+0

[This reference](http://en.cppreference.com/w/cpp/string/basic_string/basic_string),對我來說已經足夠好了。 –

回答

1

有字符文字和字符串在C++中。

例如,用'A'等單引號括起來的字符表示一個字符字面量並表示一個字符並且類型爲char

如果你會附上一個符號像"A"雙引號,那麼你得到一個字符串文字具有類型cont char[2],並具備

{ 'A', '\0' } 

內部表示這是它由兩個字符,包括終止零。

你可以看到區別運行這個簡單的porgram

#includde <iostream> 

int main() 
{ 
    std::cout << "sizeof('A') = " << sizeof('A') << std::endl; 
    std::cout << "sizeof(\"A\") = " << sizeof("A") << std::endl; 
} 

類的std :: basic_string的(或std ::字符串)具有以下構造

basic_string(size_type n, charT c, const Allocator& a = Allocator()); 

,並在此聲明

const std::string spaces(greeting.size(), ' '); 

使用此構造函數。它用greeting.size()數字的空格字符初始化字符串。

1

那是因爲你正在使用此構造函數:string (size_t n, char c)(沒有你鏈接的基準6),填補了新建成的字符串n字符c。如果您使用雙引號創建字符串文字,則單引號表示字符。

+0

我明白了,謝謝你指點我。 – Avdept

2

雙引號" "是串用C++面值(由const char [N]表示),而單引號' '是一個字符文字(char),所以你分別致電(std::size_t, const char [N])構造。

它不存在,所以你得到一個編譯錯誤。

您需要將其更改爲類似可用的構造函數:

string (size_t n, char c); 
string (const char* s); 

(你已經做了改變第二個參數' '