[英]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.