使用指针数组作为方法的参数

Using array of pointers as parameter to method

本文关键字:方法 参数 指针 数组      更新时间:2023-10-16

我必须使用指向对象的指针数组,并且还必须将其作为参数传递给方法。然而,我不知道该怎么做。下面是我用来初始化数组元素的方法。当我在main中解引用它们时,它们的数据不正确(它们包含内存地址)。正确的方法是什么?我对它们的解读可能是错误的吗?

void createSquares(Square* squareArray[]){
    PropertySquare PropertySquare1(1,"purple",120);
    PropertySquare PropertySquare2(2,"purple",170);
    squareArray[1] = &PropertySquare1;
    squareArray[2] = &PropertySquare2;
.
.
.
}

In main:

Square *allSquares[22] ;
createSquares(allSquares);
cout<<"ID is: "<<allSquares[1]->getID()<<endl;
cin.get();

正如我所说,ID最终是一个内存地址。


基于答案更新

我试过这个,它不工作,以及。我必须使用多态性。

vector<Square*> allSquares;
createSquares(allSquares);
void createSquares(vector<Square*> &squares){
PropertySquare PropertySquare1(1,"purple",120);
PropertySquare PropertySquare2(2,"purple",170);
squares.push_back(&PropertySquare1);
squares.push_back(&PropertySquare2);
}
在主要

:

for (vector<Square*>::iterator it=allSquares.begin(); it!=allSquares.end();it++){
   it->
}

它不允许我使用Square的虚函数,因为它是抽象的。任何建议吗?

你做的每件事都不好。要知道从哪里开始是很棘手的,所以让我从最后开始,并呈现正确的方式:

typedef std::unique_ptr<Square> square_ptr;
void createSquares(std::vector<square_ptr> & v)
{
  v.emplace_back(new PropertySquare1(1,"purple",120));
  v.emplace_back(new PropertySquare1(2,"green",370));
  // ...
}
int main()
{
  std::vector<square_ptr> allSquares;
  createSquares(allSquares);
  for (const auto & p : allSquares)
    std::cout << "ID is: " << p->getID() << std::endl;
}

现在来分析一下你的问题:

首先,存储的是局部变量的指针。这些局部变量在函数作用域结束时死亡,指针变得悬空。解引用是程序错误。

其次,要解决这个问题,您应该创建动态对象:squareArray[1] = new PropertySquare1(1,"purple",120);然而,这也是有问题的。得有人把这些东西清理干净!您可以遍历数组并对每个元素调用delete

第三,22是一个"幻数"(因为它既不是0也不是1)。这不应该是硬编码的。如果该数字确实是编译时常量,则在某处命名。

第四,不管怎样,不要使用原始数组。如果大小在编译时已知,则使用std::array;如果大小在运行时确定,则使用std::vector

第五,综上所述,一个智能指针的动态容器解决了你所有的烦恼。这是我代码中呈现的。另一种方法是智能指针的静态数组,它根本不需要初始化函数,而是在初始化时立即进行初始化:

const std::size_t nfuncs = 22;
std::array<square_ptr, nfuncs> allSquares {
  new PropertySquare1(1,"purple",120),
  new PropertySquare1(2,"green",370),
  // ...
};

错误的是

PropertySquare PropertySquare1(1,"purple",120);
PropertySquare PropertySquare2(2,"purple",170);

createSquares返回时销毁。输出id时,数组中包含垃圾

因为PropertySquare变量是在堆栈中声明的,一旦函数返回,它们将被销毁。你想用

在堆中声明它们
squareArray[1] = new PropertySquare PropertySquare1(1,"purple",120);
squareArray[2] = new PropertySquare PropertySquare1(2,"purple",170);

,并通过调用delete allSquares[1]等在main中删除它们