【问题标题】:Vector Isn't Creating Multiple Class ObjectsVector 不会创建多个类对象
【发布时间】:2023-03-24 05:21:01
【问题描述】:

我有一个vector 存储多个class objects 供以后访问。这样我的程序可以在运行时创建新的objects。这样做是这样的:

vector<Person> peopleVector;
peopleVector.push_back(Person(name, age));
for (int i = 0; i < peopleVector.size(); i++) {
    cout << peopleVector[i].name << endl;
}

这个函数应该在每次代码运行时打印出每个objects“名字”(这是一个运行多次的函数)。但是,当我运行它时,不知何故 vector 的大小不会增加。如果您将cout &lt;&lt; peopleVector.size(); 添加到该代码中,您会发现每次运行时都会得到一个(显然假设您还拥有我在下面的class 代码)。

我很好奇为什么我不能在课堂上创建多个objects。

类.h

#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;
}

Main.cpp

#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;
    }
}

仅供参考,那些 #includes 可能有点偏离,因为我从包含 15 个包含的大部分代码中取出了该代码。

【问题讨论】:

  • 在您的示例中您从未调用过newPerson,那么您期望会发生什么?另外,每次调用newPerson 时,您都会不断创建一个新的std::vector&lt;Person&gt;,这样vector 将永远不会大于1 的大小

标签: c++ class object vector


【解决方案1】:

每次调用 newPerson() 函数时都会创建一个空向量,然后向其中添加一个人。

然后显示该向量的内容。除了你添加的那个人,它还能包含什么?

【讨论】:

    【解决方案2】:

    问题

    每次函数运行时,函数内的所有局部变量都会以默认状态重新创建。这意味着每次调用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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多