深入理解各種建構函式

2021-08-26 06:31:30 字數 1100 閱讀 8085

#include#includeusing namespace std; class test else } test(const test & t) else } test &operator = (const test & t) pdata = new char [strlen(t.pdata) + 1]; strcpy(pdata , t.pdata); } else return * this; } ~test() void set( char*value) else } private: char * pdata; }; test fun( test aa) int main()

執行結果如下:

this is construction of test 1111 //a的建構函式

this is copy construction of test 1111 //傳值產生的結果,即a拷貝了乙個aa

this is construction of test 0000 //bb的建構函式

this is operator = : 0000= 1111 //bb=aa的結果

this is copy construction of test 2222 //return bb;用bb構造了乙個b,所以呼叫的是拷貝建構函式

this is dectruction of test 2222 //bb的析構函式

this is dectruction of test 1111 //aa的析構函式

this is copy construction of test 1111 //語句test c = a 的建構函式,這裡沒有呼叫operator=,因為拷貝建構函式效率更高,算是一種優化把

this is operator = : 1111= 2222 //a=b操作的結果

this is dectruction of test 1111 //c的析構函式

this is dectruction of test 2222 //b的析構函式

this is dectruction of test 2222 //a的析構函式

press any key to continue

俗話說得好,好記性不如爛筆頭啊,自己寫得**,現在居然看不懂了……

C 建構函式深入理解

01 初始化引數列表.cpp include include include using namespace std struct student 拷貝建構函式定義 拷貝建構函式的有效引數,必須是該類的物件的引用 if 1 student student s,int class no 1 else ...

深入理解js建構函式

在j ascript中,建立物件的方式包括兩種 物件字面量和使用new表示式。1.1物件字面量是一種靈活方便的書寫方式,例如 var o1 這樣,就用物件字面量建立了乙個物件o1,它具有乙個成員變數p以及乙個成員方法alertp。這種寫法的缺點是 每建立乙個新的物件都需要寫出完整的定義語句,不便於建...

深入理解Android View的建構函式

原文 a deep dive into android view constructors 我經常看到關於android view構造方法的困惑。為什麼有四個構造方法?每個引數是做什麼的?我需要實現哪個構造方法?如果你想要乙個直接而實際的建議,這裡有幾個不錯的指導原則 對於那些仍和我一樣想繼續 的人...