日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

copy构造函数使用深copy

發布時間:2025/3/15 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 <iostream>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

總結

以上是生活随笔為你收集整理的copy构造函数使用深copy的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。