在c++中推回基类类型2d vector中的子类对象



我真的搜索了整个互联网,找不到解决它的方法,所以这是我的问题:

我创建了一个名为"Gridpoint"的类来表示2d地图上的每个点,然后创建了一个Gridpoint*类型的2d向量来存储和打印整个地图(n^2 Gridpoint对象)

此外,我有一个名为"船"的基类(通常包含船舶)和6个子类,用于各种类型的船舶,具有有关它们的额外功能(例如。"海盗")。

所以,我想创建一个类型为Ship*的空2d向量,其中有6行,每行存储每个子类创建的对象。(例如第4排->所有海盗船)。

然而,尽管所有对象(来自Ship子类)都被成功创建,vector中没有存储任何东西,它仍然为空。

我应该怎么做才能成功地在正确的行push_back每个对象,它被创建的那一刻?

下面是"参与"vector和对象的创建和push_back的所有函数的简化版本(仅适用于子类Pirate)。更多信息或代码,请问我:

void createShip0(vector<vector<GridPoint*>, vector<vector<Ship*> >, int, int, double, double, int, int, int)
int main()
{
    int n = 10;
    vector<GridPoint*> gcol(n);
    vector<vector<GridPoint*> > GridMap(n, gcol);
    vector<vector<Ship*> > ShipArray(7);
    int i = rand() % n;
    int j = rand() % n;
    double MxEnd = rand() % 5 + 5;
    int Sped = rand() % 3 + 1;
    createShip0(GridMap, ShipArray, i, j, MxEnd, MxEnd, Sped, 0, n);
}

void createShip0(vector<vector<GridPoint*> > GridMap, vector<vector<Ship*> > ShipArray, int xIn, int yIn, double MaxEnd, double CurEnd, int Speed, int TreasQ, int n)
{
    Pirate::createShip(GridMap, ShipArray, xIn, yIn, MaxEnd, CurEnd, Speed, TreasQ);
}

void Pirate::createShip(vector<vector<GridPoint*> > GridMap, vector<vector<Ship*> > ShipArray, int xIn, int yIn, double MaxEnd, double CurEnd, int Speed, int TreasQ)
{
    Pirate* obj = new Pirate(xIn, yIn, MaxEnd, CurEnd, Speed, TreasQ);
    ShipArray.at(3).push_back(obj); 
}

您的createShip0函数按值接受其所有参数,这意味着它们是函数体中的本地副本,在调用方不可见。你正在做的相当于这个:

void foo(int n) { n += 42; }
然后

int i = 0;
foo(i);
stc::cout << i << std::endl; // Output: 0

,期望i42增加。如果您希望在调用方修改函数的参数,则需要通过引用传递它们:

void foo(int& n) { n += 42; }
//          ^

最新更新