考慮下面的程序。基本上我有一個名爲Person的struct
,默認爲name="NO NAME"
和age = 0
。現在我首先創建一個向其添加5 Person
的向量。即使在調試器中運行,for循環結束後,它只有一個5尺寸的向量,默認爲Person
。但是當我去打印它時,出現了一些問題。將struct傳遞給vector,打印vector給出奇怪的結果
我首先通過const
載體,因爲我沒有改變任何東西。使用printf
,我這樣做:list_of_persons.at(i).name, list_of_persons.at(i).age
,只打印出人的姓名和年齡。你會期望它是NO NAME
和0
,因爲我沒有改變默認值,但我的CMD給了我不同的方式,我不知道爲什麼?
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main();
struct Person {
string name = "NO NAME";
int age = 0;
};
void print_vector(const vector <Person> &);
int main()
{
vector<Person> list_of_persons;
for (unsigned int i = 0; i < 5; i++)
{
struct Person p;
list_of_persons.push_back(p);
}
print_vector(list_of_persons);
printf("\n");
system("pause");
return 0;
}
void print_vector(const vector<Person>& list_of_persons)
{
for (unsigned int i = 0; i < list_of_persons.size(); i++)
{
printf("Person %d \n", i);
printf("Name: %s\nAge: %d \n \n", list_of_persons.at(i).name, list_of_persons.at(i).age);
}
}
C和C++是_different languages_! – ForceBru