我有一个vector
,其中存储了多个class
object
,供以后访问。这样,我的程序可以在运行时创建新的object
。这样做是这样的:
vector<Person> peopleVector;
peopleVector.push_back(Person(name, age));
for (int i = 0; i < peopleVector.size(); i++) {
cout << peopleVector[i].name << endl;
}
此函数应在每次代码运行时打印出每个object
的“名称”(此函数可以运行多次)。但是,当我运行此命令时,vector
的大小不会增加。如果在该代码中添加cout << peopleVector.size();
,您会发现它每次运行都会得到一个(显然,假设您也有下面的class
代码)。
我很好奇为什么不能在课堂上创建多个object
。
#pragma once
#include <iostream>
using namespace std;
class Person {
public:
Person(string personName, int personAge);
string name;
int age;
};
Person::Person(string personName, int personAge) {
name = personName;
age = personAge;
}
#include "Class.h"
#include <random>
int main() {
// Necessary for random numbers
srand(time(0));
string name = names[rand() % 82]; // Array with a lot of names
int age = 4 + (rand() % 95);
}
// Create a new person
void newPerson(string name, int age) {
vector<Person> peopleVector;
peopleVector.push_back(Person(name, age));
for (int i = 0; i < peopleVector.size(); i++) {
cout << peopleVector[i].name << endl;
}
}
仅供参考,这些#include
可能会有些偏离,因为我从包含15个include的较大部分中提取了该代码。
答案 0 :(得分:2)
每次调用newPerson()
函数时,您将创建一个空向量,然后向其中添加一个人。
然后显示该向量的内容。除了您添加的一个人以外,它还能包含什么?
答案 1 :(得分:0)
每次运行函数时,函数内部的所有局部变量都将以其默认状态重新创建。这意味着每次您调用newPerson
时,它只会重新创建peopleVector
。
有两种解决方案:
newPerson
引用一个向量,并将其添加到该向量上peopleVector
设为静态,这样就不会每次都重新初始化// Create a new person; add it to peopleVector
// The function takes a reference to the vector you want to add it to
void newPerson(string name, int age, vector<Person>& peopleVector) {
peopleVector.push_back(Person(name, age));
for (int i = 0; i < peopleVector.size(); i++) {
cout << peopleVector[i].name << endl;
}
}
peopleVector
标记为static
// create a new person; add it to peopleVector
void newPerson(string name, int age) {
// Marking peopleVector as static prevents it from being re-initialized
static vector<Person> peopleVector;
peopleVector.push_back(Person(name, age));
for (int i = 0; i < peopleVector.size(); i++) {
cout << peopleVector[i].name << endl;
}
}