C++ 類 拷貝構(gòu)造函數(shù)

/* class constructor && desctructor */

/* 新建一個對象, 使用老的對象賦值,實際上是調(diào)用的拷貝構(gòu)造函數(shù) */

#include <iostream>

using namespace std;

class Line {

private :

int *ptr;

public:

/* constructor */

Line(int len);

Line(const Line &old);

/* destructor */

~Line(void);

void setLength(int len);

int getLength();

};

Line::Line(int len)

{

? ptr = new int;

? *ptr = len;

}

Line::~Line()

{

cout << "Destructor!" << endl;

delete ptr;

}

Line::Line(const Line &old)

{

ptr = new int;

*ptr = *old.ptr;

}

void Line::setLength(int len)

{

*ptr = len;

}

int Line::getLength()

{

return *ptr;

}

int main()

{

/* old obj */

Line l(10);

cout << "Line:" << l.getLength() << endl;

/* copy construct1 */

Line l2(l);

cout << "Line2 :" << l2.getLength() << endl;

/* copy construct2 */

/*?Line l3 = l2;? < == > Line 3(l2);? */

Line l3 = l2;

cout << "Line3 :" << l3.getLength() << endl;

return 0;

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容