在c ++中调整动态对象数组的大小

时间:2014-03-02 04:21:13

标签: arrays visual-c++ object dynamic

您好我正在开发一个项目,我从文件中访问信息,然后将其放入一个对象数组中,然后从菜单中的选项操作对象中的数据。我目前遇到的问题是菜单中的一个选项是向对象添加一个新元素。该项目声明我必须使用一个对象数组,所以我不能只使用一个向量我将数组放入其中的类来调整大小,它使用临时动态数组作为对象然后删除原始阵列。

这是班级的样子

class Info
{
private:
   string name;
   double money;
public:
   Info(){
     name=""; 
     money=0;
   }

   void Setname(string n){
     name=n;
   }
   void Setmoney(double m){
     money=m;
   }
   string GetName()const{
      return name;
   }
   double GetMoney()const{
      return money;
   }
};

现在这只是该类的一个样本,实际的类具有方程式来改变货币变量但是为了这个问题的目的,这就是所需要的。现在这里是我遇到问题的功能

void Addinfo(Info in [], int & size){
      string newname;
      double newmoney;
      cout<<"What name are you going to use?"<<endl;
      cin>>newname;
      cout<<"Now How much money do you have currently"<<endl;
      cin>>newmoney;
      Info *temp= new Info[size+1];
      for(int index=0; index<size;index++){
          temp[index].Setname(in[index].GetName());
          temp[index].Setmoney(in[index].GetMoney());
      }
      delete []in;
      temp[size].Setname(newname);
      temp[size].Setmoney(newmoney);
      in=temp;
      size=size+1;
}

现在,当我运行程序时,一切运行正常,直到我尝试使用此函数,其中数组中的数据被破坏。我应该在Info变量中创建一个新的动态数组,它可以保存所有信息,然后使用另一个for循环将变量放入新的动态数组中,或者我应该做其他事情。还要记住我必须为此使用数组。同样在删除动态数组时我应该在删除后使前一个数组等于零,还是那个别的?

1 个答案:

答案 0 :(得分:0)

当你有一个type valueName[]数组参数的函数时,你只需将该数组参数的地址传递给该函数。调用函数具有该数组的所有权。除了函数签名之外,您还必须考虑调用者和被调用函数之间的契约,该契约定义了指针传递的数据的所有权。

您的函数AddInfo获取一个由指针传递的数组,并且调用函数期望在函数调用之后数据可用。因此,当您delete []in时,该功能违反了合同。

当您使用in分配新值时,您的函数使用参数in=temp;作为(本地)变量。那是合法的。但是你不能指望改变的局部变量对调用者有任何影响。使用当前函数签名可以以这种方式调用函数:

Info infos[5];
Addinfo(&info[3], 2);

显然修改&info[3]毫无意义。当您的合同允许向阵列添加一些数据时,您需要一个允许更改指针的签名。一个例子是:

void Addinfo(Info*& in, int& size, string newname, double newmoney)
{
  Info *temp= new Info[size+1];
  for(int index=0; index<size;index++){
      temp[index].Setname(in[index].GetName());
      temp[index].Setmoney(in[index].GetMoney());
  }
  temp[size].Setname(newname);
  temp[size].Setmoney(newmoney);
  delete []in;
  in = temp;
  size=size+1;
}

void Addinfo(Info*& in, int& size)
{
  string newname;
  double newmoney;
  // input data
  cout<<"What name are you going to use?"<<endl;
  cin>>newname;
  cout<<"Now How much money do you have currently"<<endl;
  cin>>newmoney;
  // TODO: data validation.
  // add data to array
  Addinfo(in, size, newname, newmoney);
}

我已经考虑了输入中数组的更改。这样可以更简单地测试该功能。