copy构造函数使用深copy

=操作符的默认copy构造函数是浅copy,要是想使用深copy需要编写copy构造函数,编写深copy构造函数的形式如下,调用方式除了显示的调用,当首次定义对象,并使用=进行对象初始化的时候也会调用该copy构造函数 Array a2 = a1;

Array::Array(const Array& obj)
{
  this->m_length = obj.m_length;
  this->m_space = new int[this->m_length]; //分配内存空间

  for (int i=0; i<m_length; i++) //数组元素复制
  {
  	this->m_space[i] = obj.m_space[i];
  }
}

#include "myarray.h"

//

//int m_length;
//char *m_space;
Array::Array(int length)
{
	if (length < 0)
	{
		length = 0; //
	}

	m_length = length;
	m_space = new int[m_length];
}

//Array a2 = a1;
// 当首次定义对象并调用 = 操作符的时候,调用该深copy构造函数,其他时候的 =就是=操作符
Array::Array(const Array& obj)
{
	this->m_length = obj.m_length;
	this->m_space = new int[this->m_length]; //分配内存空间

	for (int i=0; i<m_length; i++) //数组元素复制
	{
		this->m_space[i] = obj.m_space[i];
	}
}
Array::~Array()
{
	if (m_space != NULL)
	{
		delete[] m_space;
		m_space = NULL;
		m_length = -1;
	}
}

//a1.setData(i, i);
void Array::setData(int index, int valude)
{
	m_space[index] = valude;
}
int Array::getData(int index)
{
	return m_space[index];
}
int Array::length()
{
	return m_length;
}


test.cpp函数

#include 

using namespace std;


class TestCopy
{
private:
    /* data */
    int legth;
    int *pArray;
public:
    TestCopy(int len);
    ~TestCopy();
    // TestCopy t2 = t1;  特殊构造函数   当首次定义t2并调用=的时候,就会调用该构造函数
    TestCopy(TestCopy & test);
    int setArray(int index, int valued);
    int getLength(void);
    int printArray(int index);
};

TestCopy::TestCopy(int len)
{
    if(len < 0)
    {
        len = 0;
    }

    legth = len;
    pArray = new int[len];

}

TestCopy::~TestCopy()
{
        if(pArray != NULL)
        {
            delete[] pArray;
            legth = -1;
        }
}

TestCopy::TestCopy(TestCopy & test)
{
    this->legth = test.legth;
    this->pArray = new int[this->legth];

    for (int i = 0; i < this->legth; i++)
    {
        this->pArray[i] = test.pArray[i];
    }
    cout << "construct function is called"  << endl;
}


int TestCopy::setArray(int index, int valued)
{
    this->pArray[index] = valued;
    return 0;
}


int TestCopy::getLength(void)
{
    return this->legth;
}


int TestCopy::printArray(int index)
{
    cout << this->pArray[index] << endl;
    return 0;
}

int main(int argc, const char** argv) 
{    
    
    TestCopy t1(10);
    
    for(int i = 0; i < t1.getLength(); i ++)
    {
        t1.setArray(i, i);
    }

    // 开始调用构造函数
    cout << "---------------------start-----------------" << endl;

    TestCopy t2 = t1;

    cout << "----------------------end------------------" << endl;
    for(int i = 0; i  < t2.getLength(); i++)
    {
        t2.printArray(i);
    }

    
    
    
    return 0;
}




输出结果:

$ ./a.out 
---------------------start-----------------
construct function is called
----------------------end------------------
0
1
2
3
4
5
6
7
8
9

你可能感兴趣的:(C-C++)