我确实在整个互联网上进行了搜索,却找不到解决它的方法,所以这是我的问题:
我创建了一个名为“ Gridpoint”的类来表示2d地图的每个点,然后创建一个Gridpoint *类型的2d向量来存储和打印整个地图(n ^ 2个Gridpoint对象)
另外,我有一个名为“ Ship”的基类(通常包含船),还有6个用于各种类型船的子类,它们具有额外的功能(例如“ Pirate”)。
因此,我想创建一个Ship *类型的空2d向量,该向量具有6行以在每个行中存储每个子类创建的对象。(例如第4行->所有海盗船)。
但是,尽管所有对象(来自Ship子类)均已成功创建,但此向量中始终没有存储任何内容,并且它保持为空。
创建对象后,应该如何正确地将对象正确推入正确的行?
以下是“参与”向量和对象的创建以及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
并期望i
增加42
。如果要在调用方修改函数的参数,则需要通过引用传递它们:
void foo(int& n) { n += 42; }
// ^
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句