gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:38:43 25 4
gpt4 key购买 nike

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;
}

最佳答案

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

 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
}

关于C++ 复制构造函数和赋值运算符定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com