gpt4 book ai didi

c++ - 访问类的数组成员时出现段错误

转载 作者:行者123 更新时间:2023-11-28 05:54:56 25 4
gpt4 key购买 nike

我的程序中有类Field和Cell,还有一些类继承自Cell。 Main 函数与 Field 一起工作,Field 有一个数组成员,其中包含指向不同类的单元格的指针。单元格是用一种方法创建的,当我尝试用另一种方法访问它们时出现段错误。我觉得一定是创建了一个错误的数组,但不知道如何修复它。我试图将指针数组更改为单元格数组,但即使在程序的早期阶段也会出错。

为避免在此处放置过多代码:在主函数中,第一个字段创建为 Field myfield;,然后为其调用函数:SetName、SetSize、CreateCells。然后我尝试用下一个函数绘制 ConsoleDraw(&myfield); 一个字段:

void ConsoleDraw(Field *f)
{
Cell* cell;

for (int i=0; i<f->GetHeight(); i++)
{
for (int j=0; j<f->GetWidth(); j++)
std::cout << f->GetCell(i,j)->GetType();

std::cout << std::endl;
}

std::cout << std::endl;
}

这是类的代码:
字段.h:

class Field
{
public:
//some methods
void ChangeCell(int i, int j, int type);
void CreateCells();
Cell* GetCell(int i, int j);

private:
//some variables
Cell*** cells;
};

字段.cpp:

void Field::CreateCells()
{
cells = new Cell**[height];
for (int i=0; i<height; i++)
{
cells[i] = new Cell*[width];

for (int j=0; j<width; j++)
ChangeCell(i,j,0);
}

for (int i=0; i<height; i++)
for (int j=0; j<width; j++)
cells[i][j]->SetNeighb();//operating with variables of single cell
}

void Field::ChangeCell(int i, int j, int type)
{
if (cells[i][j]) delete cells[i][j];

switch (type)
{
case 0:
cells[i][j] = new Cell(0);
break;
case 1:
cells[i][j] = new Cell(1);
break;
case 2:
{
cells[i][j] = new MovingCell;
}
break;
case 3:
{
cells[i][j] = new CreatingCell;
}
break;
case 4:
{
cells[i][j] = new KillingCell;
}
break;
case 5:
{
cells[i][j] = new DyingCell;
}
break;
default:
if (type<10)
{
cells[i][j] = new DyingCell;
cells[i][j]->SetChar(type-4);
}
else
{
cells[i][j] = new MovingCell;
GetCell(i,j)->SetChar(type-10);
}
}

cells[i][j]->SetCoordinates(j,i);
cells[i][j]->SetOwner(this);
}

Cell* Field::GetCell(int i, int j)
{
return cells[i][j]; //Here I got an error.
}

我认为没有必要发布Cell类,因为所有问题都是在操作Field时出现的。预先感谢您提供正确初始化该数组的任何想法。

最佳答案

if (cells[i][j]) delete cells[i][j]; 假定所有单元格都已分配了 new,但是有在下面的 switch 语句中,很多情况下单元格没有分配 new 而是指向共享位置。这对我来说看起来很不干净,肯定会导致段错误。

下一个错误:您在 ChangeCell 的 switch 语句的 default 子句中将指针分配给临时对象。对它们的任何访问迟早会导致段错误。对它们的任何 delete 调用都会导致段错误。

关于c++ - 访问类的数组成员时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com