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

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

问题描述:

我已经在C++中创建了一个类来处理0和1的数组。在私有属性中,我有一个大小,一个类型和指定大小的整数数组。再次调用构造函数时会修改对象的C++私有成员

我的问题是,每次我再次调用构造函数时,数组中的值正在被修改。更详细地说,我用构造函数创建第一个对象,然后创建第二个对象,并修改第一个对象!

我试过玩弄指针,新的操作符,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; 
} 
+0

你能发布一个完整的测试用例?如果我们看不到相关的代码,很难猜测问题是什么。 – 2012-02-07 12:24:49

+0

不是一个错误,但为什么你写'(test3).print();'而不是'test3.print();'?额外的大括号看起来对我来说很奇怪... – catchmeifyoutry 2012-02-07 12:28:00

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

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

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

+1

'Table'不是OP代码中的指针类型... – 2012-02-07 12:26:02

+0

甚至更​​好,你使用'std :: vector ' – KillianDS 2012-02-07 12:28:27

+0

@OliCharlesworth:绝对,我的错误。所以有什么地方丢失了... – patriiice 2012-02-07 12:31:34

罪魁祸首是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; 
     } 
    } 
}; 
+0

天才,非常感谢你! – 2012-02-08 06:04:38