我正在使用Visual Studio 2017 for School在cpp中开发一个模拟游戏,在开发阶段我陷入了这种情况。
因此,我要做的是创建一个新项目,以尝试以最简单的形式重新创建该问题,以便于调试。

以下是主文件和所有相关的源代码:

main.cpp

#include "header.h"
#include "Vehicle.h"
#include "Car.h"

int main() {

    Vehicle v;

    v.addCar(1);
    v.addCar(2);
    v.addCar(3);


    cout << v.getCars()[1].id << endl;
    v.getCars()[1].id = 99;
    cout << v.getCars()[1].id << endl;
    system("pause");
    return 0;
}


头文件

#ifndef CLUSTE2R_H
#define CLUSTE2R_H
#pragma once
#include <iostream>
#include <vector>
using namespace std;
#endif


汽车

#ifndef CLUSTE1R_H
#define CLUSTE1R_H
#pragma once
#include "Vehicle.h"

using namespace std;


class Car : public Vehicle
{
public:
    int id;
    Car(int id);
    ~Car();
};

#endif


Car.cpp

#include "Car.h"

Car::Car(int id)
{
    this->id = id;
}


Car::~Car()
{
}


车辆

#ifndef CLUSTER_H
#define CLUSTER_H
#pragma once

#include <vector>
//#include "Car.h"

class Car;
using namespace std;


class Vehicle
{
private:
    vector<Car> cars;

public:
    Vehicle();
    ~Vehicle();

    vector<Car> getCars();
    void addCar(int id);

};

#endif


Vehicle.cpp

#include "Vehicle.h"
#include "Car.h"
#include <vector>

using namespace std;
//class Car;
Vehicle::Vehicle()
{
}


Vehicle::~Vehicle()
{
}


vector<Car> Vehicle::getCars()
{
    return this->cars;
}

void Vehicle::addCar(int id)
{
    Car c(id);

    cars.reserve(cars.size() + 1);
    cars.push_back(c);
}


所以,我想做的是获得以下输出:


  2 \ n 99


这就是我得到的:


  2 \ n 2


我究竟做错了什么?我相信问题与main.cpp文件有关。但是我不太确定如何以其他方式实现我想要的...

最佳答案

当前,当您从Vehicle调用getCars()函数时,您正在返回向量的新实例,这意味着对该向量的所有更改都不会应用于该类中的原始向量。

为了解决这个问题,您可以返回向量的引用(将vector<Car> getCars();更改为std::vector<Car>& getCars())。

您还可以在本地创建矢量的副本,然后将矢量设置为该类。

10-06 08:17