copy構造関数深さcopyを使用

20001 ワード

=オペレータのデフォルトの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