【问题标题】:Can I update an object inside an array?我可以更新数组中的对象吗?
【发布时间】:2020-06-12 07:17:55
【问题描述】:

所以我创建了一个对象,然后将它添加到一个数组中

Class Item{
...
};

Class Machine{
   void setQuantity(int i);
};

Machine::Machine(){
   Item items[5];

   items[0] = a(int q);
}

我定义了 setQuantity(),然后在后面的代码中尝试 setQuantity,使用

items[0].setQuantity(items[0].getQuantity() + 1);

但是 a 的数量没有更新。是因为我无法更新数组中某项的属性还是数量无法更改?

我正在考虑将数组更改为向量,但我想知道问题是否出在数组上。如果不是,那么将其更改为向量并不重要,不是吗?

提前致谢!

int Item::getQuantity(){
     return quantity; 
}  
void Item::setQuantity(int q){
     quantity = q; 
}

items[i].setQuantity(items[i].getQuantity + 1);

【问题讨论】:

  • 确定问题不在于阵列,您想做的事完全可行;可以发一下setQuantitygetQuantity函数的详细代码吗?
  • int Item::getQuantity(){ return quantity; } void Item::setQuantity(int q){ quantity = q; }
  • 我在for循环中也改了,所以更像items[i].setQuantity(items[i].getQuantity + 1);
  • 在不同的函数中调用它是否重要?
  • 请将您的代码编辑到问题中。注释不能很好地处理代码,可能会被删除。使用您的代码编辑您的问题。

标签: c++ arrays oop vector


【解决方案1】:

我认为这里的问题是您在函数调用a() 中声明了一个变量,根据列出的代码,它是未定义的。

int q 是变量声明的语法,但尚未为 q 定义值。

对于您创建的 5 个items 中的每一个,都会调用 Item 类的默认构造函数。

如果您想为items[0] 赋值,您可以(并且可能应该)在Item 中实现赋值运算符和复制构造函数。或者您可以在数组中存储指向Item 的指针而不是对象本身,然后使用items[0] = new Item(...) 来分配项目。

【讨论】:

  • Item::Item(int x, string n, int p, int q, string d){ num = x; name = n; price = p; quantity = q; desc = d; } 我是这样定义的,写了完整的代码。问题中的一个是简化版本。但确实,我应该尝试指针。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-28
相关资源
最近更新 更多