浏览OP的代码并尝试解释发生了什么:
int main()
{
string word = word; // this creates a string named word and sets word
// to itself. In other words, other than creating
// word, it doesn't do anything.
// most likely the intent was
// string word = "word";
// The "" marks contained text as data to be
// Interpreted as a string
string word1; // these create more words set to the default
string word2; // empty string that don't do much for reasons explained
string word3; // below
string word4;
string word5;
string *pointer = &word; // this is good
string words[5] = { word1, word2, word3, word4, word5 };
// this created an array of 5 strings and copied the values of word1
// through word5 into array elements 0 through 4. Since word1 through 5
// contain the default value, this does nothing more than
// string words[5];
for (int i = 0; i <= 5; i++) // words contains 5 slots, 0 though 4.
// the loop conditions cover 0 through 5
// it will compile but will have undefined
// behaviour (maybe crash, maybe not)
// when words[5] is reached.
// Very likely the intent was
// for (int i = 0; i < 5; i++)
{
word[i] = *pointer; // this is most likely a typo.
// The odd message about assigning a string to
// a character is because you can use [] to
// access individual characters in a string
// just like you can an array
// words[i] = *pointer;
// is probably what was intended
cout << word[i] << endl; // this is good, but probably not what is
// intended. It will print out the
// characters in word one by one.
// as with above, it likely should be
// cout << words[i] << endl;
}
return 0;
}更正并删除了箔条我们得到
int main1()
{
string word = "word";
string *pointer = &word;
string words[5];
for (int i = 0; i < 5; i++)
{
words[i] = *pointer;
cout << words[i] << endl;
}
return 0;
}一种稍微安全的方法。我们可以通过将单词数组的总大小除以单个元素的大小来将循环绑定到单词中的字符串数。这样它就永远不会超出范围。注意我已经将i的类型从有符号的int更改为size_t,这是一个非常适合用作索引的无符号值。
int main2()
{
string word = "word";
string *pointer = &word;
string words[5];
for (size_t i = 0; i < sizeof(words)/sizeof(words[0]); i++)
{
words[i] = *pointer;
cout << words[i] << endl;
}
return 0;
}或者我们可以使用C++ 11中的增强型for循环
int main3()
{
string word = "word";
string *pointer = &word;
string words[5];
for (string & wordref: words) // note the &. In this case we are using a reference,
// a restricted pointer, to the strings in words.
// We need the reference or a pointer because
// otherwise we will be given a copy of the string
// in words, and the assignment will be to the copy,
// not to the source string in words.
{
wordref = *pointer;
cout << wordref << endl;
}
return 0;
}