在 C++ 中推回 base class 类型二维向量中的 subclass 对象

Push back subclass objects in base class type 2d vector in C++

我真的在整个互联网上搜索过,找不到修复它的方法,所以这是我的问题:

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

此外,我有一个名为 "Ship" 的基础 class(通常包含船舶)和 6 个子class 用于各种具有额外功能的船舶(例如。 "Pirate").

因此,我想创建一个 Ship* 类型的空二维向量,其中包含 6 行以在每一行中存储每个子 class 创建的对象。 (例如第 4 行 -> 所有海盗船)。

然而,虽然所有对象(来自 Ship 子 classes)都已成功创建,但向量中从未存储任何内容,它仍然是空的。

我应该如何 push_back 在正确的行成功创建每个对象??

下面是"participate"创建和push_back向量和对象的所有函数的简化版本(仅适用于subclass海盗)。有关更多信息或代码,请问我:

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

并期望 i 增加 42。如果你想在调用方修改函数的参数,你需要通过 reference 来传递它们:

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