考虑下面的程序。基本上我有一个名为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