2013-04-27 3 views
0

C++ Конструктор копирования и Оператор присваивания Определение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; 
} 
+0

Внутри вашего конструктора копий вы должны перераспределить «счет», чтобы иметь тот же размер, что и элемент «count» объекта, который вы копируете. –

+0

Если это упражнение, чтобы научиться управлять памятью, вам будет намного лучше с 'std :: vector'. –

ответ

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 
} 
+0

@MM. Thansk, исправлено, что – alexrider

+0

Спасибо! Оно работает! – 2013-04-27 10:38:18

Смежные вопросы