深淺復(fù)制問題在與類內(nèi)有指針的情況下,默認(rèn)拷貝構(gòu)造函數(shù)只會(huì)為指針賦值,使其指向被拷貝對(duì)象的指針指向的內(nèi)存地址,并不會(huì)另外單獨(dú)為其申請(qǐng)一段內(nèi)存空間;
默認(rèn)的拷貝構(gòu)造函數(shù)就只能實(shí)現(xiàn)淺復(fù)制,要達(dá)到深復(fù)制就要重載拷貝構(gòu)造函數(shù),動(dòng)態(tài)分配內(nèi)存,拷貝類對(duì)象指針?biāo)赶虻闹担?/p>
eg.
#include <iostream>#include <cstring>using namespace std;/** 拷貝構(gòu)造函數(shù) 深復(fù)制和淺復(fù)制*/class Point {public: Point() : x(0), y(0) {} Point(int x, int y) { this->x = x; this->y = y; str = new char[100]; strcpy(str, "To do Something.../n"); } int getX() { return x; } int getY() { return y; } ///淺復(fù)制 --> 默認(rèn)拷貝構(gòu)造函數(shù) /*Point(Point &p) { x = p.x; y = p.y; str = p.str; }*/ ///深復(fù)制 Point(Point &p) { x = p.x; y = p.y; str = new char[strlen(p.str) + 1]; strcpy(str, p.str); } ~Point() { delete []str; } void setStr(char *nStr) { strcpy(str, nStr); } void showStr() { cout << str << endl; }PRivate: int x, y; char *str;};int main(){ cout << "First Point object" << endl; Point p(6, 8); cout << p.getX() << endl; cout << p.getY() << endl; p.showStr(); ///淺復(fù)制 cout << "Second Point object" << endl; Point q(p); cout << q.getX() << endl; cout << q.getY() << endl; q.showStr(); cout << "Change first object string/n" << endl; p.setStr("New Word!"); /** 指向同一個(gè)字符串 釋放內(nèi)存時(shí)被釋放了兩次 */ p.showStr(); q.showStr(); return 0;}調(diào)用拷貝構(gòu)造函數(shù) 1.當(dāng)用類的一個(gè)對(duì)象去初始化該類的另一個(gè)對(duì)象時(shí);(XXX p(q) 或 XXX p = q)
2.如果函數(shù)的形參是類的對(duì)象,調(diào)用函數(shù)時(shí),進(jìn)行形參和實(shí)參的結(jié)合時(shí); (形參為引用變量除外)
3.如果函數(shù)的返回值是類的對(duì)象,函數(shù)執(zhí)行完成返回調(diào)用者時(shí);(默寫IDE做了一些優(yōu)化,導(dǎo)致并不會(huì)調(diào)用)參考
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注