copy构造函数使用深copy
生活随笔
收集整理的這篇文章主要介紹了
copy构造函数使用深copy
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
=操作符的默認(rèn)copy構(gòu)造函數(shù)是淺copy,要是想使用深copy需要編寫(xiě)copy構(gòu)造函數(shù),編寫(xiě)深copy構(gòu)造函數(shù)的形式如下,調(diào)用方式除了顯示的調(diào)用,當(dāng)首次定義對(duì)象,并使用=進(jìn)行對(duì)象初始化的時(shí)候也會(huì)調(diào)用該copy構(gòu)造函數(shù) Array a2 = a1;
Array::Array(const Array& obj) {this->m_length = obj.m_length;this->m_space = new int[this->m_length]; //分配內(nèi)存空間for (int i=0; i<m_length; i++) //數(shù)組元素復(fù)制{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; // 當(dāng)首次定義對(duì)象并調(diào)用 = 操作符的時(shí)候,調(diào)用該深copy構(gòu)造函數(shù),其他時(shí)候的 =就是=操作符 Array::Array(const Array& obj) {this->m_length = obj.m_length;this->m_space = new int[this->m_length]; //分配內(nèi)存空間for (int i=0; i<m_length; i++) //數(shù)組元素復(fù)制{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函數(shù)
#include <iostream>using namespace std;class TestCopy { private:/* data */int legth;int *pArray; public:TestCopy(int len);~TestCopy();// TestCopy t2 = t1; 特殊構(gòu)造函數(shù) 當(dāng)首次定義t2并調(diào)用=的時(shí)候,就會(huì)調(diào)用該構(gòu)造函數(shù)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);}// 開(kāi)始調(diào)用構(gòu)造函數(shù)cout << "---------------------start-----------------" << endl;TestCopy t2 = t1;cout << "----------------------end------------------" << endl;for(int i = 0; i < t2.getLength(); i++){t2.printArray(i);}return 0; }輸出結(jié)果:
$ ./a.out ---------------------start----------------- construct function is called ----------------------end------------------ 0 1 2 3 4 5 6 7 8 9總結(jié)
以上是生活随笔為你收集整理的copy构造函数使用深copy的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2015年《大数据》高被引论文Top10
- 下一篇: 基于炼铁大数据智能互联平台推动传统工业转