使用指针数组作为方法的参数
Using array of pointers as parameter to method
我必须使用指向对象的指针数组,并且还必须将其作为参数传递给方法。然而,我不知道该怎么做。下面是我用来初始化数组元素的方法。当我在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中删除它们
相关文章:
- c++方法参数只能在linux的发布模式下自行更改
- 使用移动语义:右值引用作为方法参数
- 无法将动态创建的对象数组从 qml 发送到 c++ 作为方法参数
- 将方法参数类型更改为子类中的派生类
- ofstream作为C 中的方法参数
- 使用 gmock 匹配器将 std::function 设置为 EXPECT_CALL 中的方法参数
- C com 方法参数扣除
- 获取非静态方法参数计数
- 使用 gmock 返回模拟方法参数
- 运行 QML 时出现"未知方法参数类型"错误
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- 将C 方法参数转换为模板参数会因编译错误而失败
- 如何在方法参数中使用boost :: asio :: buffer
- qsharedPointer作为方法参数或方法的返回值的良好实践
- 如何将方法指针声明为Typedef方法参数
- 方法参数中的 OpenCV 垫"预期")""
- 方法参数中的 consst* 常量
- 带有“class”详细类型说明符的方法参数
- 具有原始方法参数派生类的 C++ 重载方法参数
- C++ std::string length() 或 size() 不适用于方法参数