在嵌套类C ++中使用push_back遇到麻烦

时间:2019-07-04 01:33:54

标签: c++ vector inner-classes push-back

我无法理解将push_back与嵌套类一起使用的正确语法。

我正在创建“汽车”类的向量。在“汽车”中,结构为“ SubItems”的向量。如果在buildList函数中声明“ Cars”和“ SubItems”的实例,则我的代码可以工作,但先前迭代中的数据仍然存在。然后,我决定在相关循环内动态分配一个类和一个结构,将它们推回向量,并在每次迭代结束时删除。我尝试了许多不同的方法来纠正问题,但是仍然缺少某些内容。对于代码来说,这显然不是我正在处理的项目中的实际代码。我只是为了显示我遇到的问题而写的。

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

struct SubItems {
    std::string model;
    float price;
};

class Cars {
private:
    std::string make;
    int year;
    int numOfCars;

public:
    std::vector<SubItems> inventory;

    std::string getMake() {
        return make;
    }

    int getYear() {
        return year;
    }

    int getNumOfCars() {
        return numOfCars;
    }

    void printCar() {
        std::cout << "Make: " << getMake() << std::endl;
        std::cout << "Year: " << getYear() << std::endl;
        if (getNumOfCars() == 0) {
            std::cout << "None available" << std::endl;
        }
        else {
            for (unsigned int i = 0; i < inventory.size(); i++) {
                std::cout << "\tModel: " << inventory[i].model << std::endl;
                std::cout << "\tPrice: " << inventory[i].price << std::endl;
            }
        }
    }

};

void buildList(std::ifstream& file, std::vector<Cars>& cars) {
    int numOfCars;
    int numOfMakes;
    file.read((char*)& numOfCars, 4);

    for (int i = 0; i < numOfCars; i++) {
        //Cars car; // This works but I need the data cleared after each iteration
        Cars* car = new Cars();

        // Assume all relevant data is read in, converted, and
        // assigned appropriately. This isn't my issue.

        file.read((char*)& numOfMakes, 4); // I already verified gives expected result.
        for (int j = 0; j < numOfMakes; j++) {
            //SubItems sub; // This works but I need the data cleared after each iteration
            SubItems* sub = new SubItems();

            // Again, assume all relevant data is read in, converted, and
            // assigned appropriately. This isn't my issue.

    /*---------- This is my problem ----------*/
            car->inventory.push_back(sub);
            delete sub;
        }
/*---------- And this is my problem ----------*/
        cars.push_back(car);
        delete car;
    }
}

int main() {
    // Not relevant to issue;
}

如果将其复制/粘贴到IDE中,则会在push_back的两行都看到该问题。

0 个答案:

没有答案