0

C++ 复制构造函数和赋值运算符定义

有人可以帮我更正以下复制构造函数和赋值运算符吗?

  1. 如您所见,赋值运算符似乎运作良好;我运行它并且它有效。我是否正确定义了赋值运算符?请告诉我。

  2. 这与复制构造函数崩溃......我该如何修复复制构造函数?

请帮我。

 #include <iostream>
 using namespace std;

 class IntP
 {
 private:
    unsigned int* counts;
    unsigned int numP;
    unsigned int size;

 public:
    IntP(); // Default Constructor
    IntP(int n); // Constructor
    IntP(const IntP& a); // Copy Constructor
    IntP& operator= (const IntP& a); // Assignment Operator
    ~IntP(); // Destructor
    void printIntP() const;
 };

 IntP::IntP() // Default Constructor
 {
   counts = new unsigned int[101] (); // initialize array of size 101 to all 0s
   numP = 0;
   size = 101;
 }

 IntP::IntP(int n) // Constructor
 {
   counts = new unsigned int[n+1] (); // initialize array of size n+1 to all 0s
   counts[n] = 1;
   numP = 1;
   size = n+1;
 }

 // ????????????
 // 
 IntP::IntP(const IntP& a) // Copy Constructor
 {
   this->size = a.size;
   this->numP = a.numP;
   for (int i=0; i < (int) this->size; i++)
      this->counts[i] = a.counts[i]; 
 }

 // ??????????? 
 // Correct Implementation?
 // without delete operator, we have memory leak? but it compiles without error??? 
 IntP& IntP::operator= (const IntP& a) // Assignment Operator
 {
   if (this != &a)
   {
     delete [] counts; // Get rid of old counts
     size = a.size; 
     numP = a.numP;
     counts = new unsigned int[size+1];
     counts[size] = 1;
     for (int i=0; i < (int) this->size; i++)
        counts[i] = a.counts[i]; 
   }
   return *this;
 }

 IntP::~IntP() { delete [] counts; }

 void IntP::printIntP() const
 {
    cout << "The size of array is " << this->size << endl;
    cout << "The numP variable becomes " << this->numP << endl;

    int i = 0;
    while ( i != (int) this->size )
    {
      cout << counts[i];
      if ( i != (int) this->size-1 ) cout << " , ";
      i++;
    } 

    cout << endl << endl;
 }

 int main (void)
 {

 IntP ip2(200); 
 IntP ip3; 
 ip3 = ip2;



 IntP ip1(100); 

 cout << "Print out   ip1 object  after IntP ip1(100); " << endl; 
 ip1.printIntP(); 


 IntP ip4(ip1); 

 cout << "Print out   ip4 object  after IntP ip4(ip1); " << endl; 
 ip4.printIntP();

 system("pause"); return 0;
 }
4

1 回答 1

1

您的代码崩溃是因为您没有为复制构造函数中的计数分配内存。

 IntP::IntP(const IntP& a) // Copy Constructor
 {
   //counts = new unsigned int[a.size] (); // Add this to allocate memory for counts
   this->size = a.size;
   this->numP = a.numP;
   for (int i=0; i < (int) this->size; i++)
      this->counts[i] = a.counts[i]; //counts is unitialized
 }
于 2013-04-27T10:31:37.137 回答