再次调用构造函数时,将修改对象的C ++私有成员

时间:2012-02-07 12:19:18

标签: c++

我用C ++创建了一个类来处理0和1的数组。在私有属性中,我有一个大小,类型和指定大小的整数数组。

我的问题是,每次再次调用构造函数时,都会修改数组中的值。在更多详细说明中,我使用构造函数创建第一个对象,然后创建第二个对象并执行此操作修改第一个对象!

我试过玩指针,新的运算符,const指向const对象的指针,什么都行不通!根据我选择的数组的大小,它总是第三个,然后是数组的第六个,然后是第九个等值,它被修改为大小的值。 任何建议表示赞赏。

我的代码中的一些摘录:

class SArray
{
private:
  int SArray_Size;
  int DType;
  int Table[];
public:
  //complete constructor
  SArray::SArray(const int& tsize, const int& ttype)
  {
    SArray_Size = tsize;
    DType = ttype;
    if (ttype == 0) //random array with integer values between 0 and 1
    {
      for (int i = 0; i < getSize(); i++) 
      {
        Table[i] = rand() % 2;
      }
    }
    if (ttype == 1) //default array with only 1s
    {
      for (int i = 0; i < getSize(); i++)
      {
        Table[i] = 1;
      }
    }
  }

};

int main()
{
  const int NbRes = 15;
  //reset the random number generator
  srand(time(0));
  const SArray test3(NbRes,1);
  (test3).print();
  const SArray test1(NbRes,1);
  (test1).print();
  (test3).print();
  return 0;
}

2 个答案:

答案 0 :(得分:3)

罪魁祸首是int Table[] - 你没有说明你的桌子有多大。

您应该将其替换为std::vector<int> Table;并将其初始化为tsize

例如:

#include <vector>

class SArray
{
  private:
    int DType;
    std::vector<int> Table;
  public:
    const size_t getSize() const { return Table.size(); }
  public:
    SArray::SArray(const int tsize, const int ttype) :
      DType(ttype), Table(tsize)
    {
      int i, n = getSize();
      switch( ttype )
      {
        case 0:
          for (i = 0; i < n; ++i) 
            Table[i] = rand() % 2;
          break;
        case 1:
          for (i = 0; i < n; ++i)
            Table[i] = 1;
          break;
      }
    }
 };

答案 1 :(得分:2)

您必须为“表”分配内存。例如:

SArray::SArray(const int& tsize, const int& ttype)
{
    SArray_Size = tsize;
    DType = ttype;
    Table= new int[tsize];
    ...

不要忘记在析构函数中释放它。