![](/img/trans.png)
[英]Is there a difference between `string s(“hello”);` and `string s = “hello”;`
[英]string s = “hello” vs string s[5] = {“hello”}
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
reverse(begin(s), end(s));
cout << s << endl;
return 0;
}
打印olleh
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s[5] = {"hello"};
reverse(begin(s), end(s));
cout << *s << endl;
return 0;
}
打印hello
請幫助我理解為什么會有這種區別。 我是c ++的新手,正在使用c ++11。好的,我已從s [5] =“ hello”糾正為s [5] = {“ hello”}。
第一個是單個字符串。 第二個是五個字符串的數組,並將所有五個字符串初始化為相同的值。 但是,允許在問題中使用語法是一個錯誤(請參閱TC注釋中的鏈接),通常應該會給出錯誤。 正確的語法將字符串放在大括號內,例如{ "hello" }
。
無論如何,在第二個程序中,您只打印五個字符串中的一個,即第一個。 取消引用數組時,它會衰減為指針,並為您提供指針指向的值,該值是數組中的第一個元素。 *s
和s[0]
是等效的。
我認為您正在尋找的是:
int main() {
char s[] = "hello";
reverse(s, s + (sizeof(s) - 1));
cout << string(s) << endl;
return 0;
}
使用char[6]
可以得到一個C風格的字符串。 請記住,這些字符串必須以'\\0'
結尾。 因此,有一個第六要素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.