copy 賦值建構函式的4種呼叫時機or方法

2021-07-03 05:34:58 字數 1486 閱讀 9367

第一種呼叫方法:

demo

#include using namespace std;

class text

text(int a) // 有引數建構函式

text(int a, int b) // 有引數建構函式,有三種呼叫方法

// 賦值建構函式,也叫copy建構函式

text(const text& obj)

~text();

void printt()

private:

int m_a;

int m_b;

};// 1 賦值建構函式,用1個物件去初始化另外乙個物件

int main()

第二種呼叫方法:

demo

// 第二種呼叫方法

int main()

第三種呼叫方法:

demo

#include using namespace std;

class location

// copy建構函式,完成物件的初始化

location(const location & obj)

~location()

int getx()

int gety()

private:

int x, y;

};// 業務函式,形參是乙個元素

void f(location p)

void playobj()

int main()

第四種呼叫方法: 

demo

#include using namespace std;

class location

// copy建構函式,完成物件的初始化

location(const location & obj)

~location()

int getx()

int gety()

private:

int x, y;

};//g函式返回乙個元素

//結論1 : 函式的返回值是乙個元素 (複雜型別的), 返回的是乙個新的匿名物件(所以會呼叫匿名物件類的copy建構函式)

////結論2: 有關 匿名物件的去和留

//如果用匿名物件,初始化另外乙個同型別的物件, 匿名物件,轉成有名物件

//如果用匿名物件,賦值給另外乙個同型別的物件, 匿名物件,被析構

////這麼寫**,設計編譯器的大牛們:

//就返回乙個新物件(沒有名字 匿名物件)

location g()

//void objplay2()

//void objplay3()

void objplay4()

拷貝建構函式和賦值構造函式呼叫次序

class cprintelement cprintelement cprintelement const cprintelement temp cprintelement cprintelement operator const cprintelement temp int main cprint...

copy構造函式呼叫時機4,函式返回值是匿名物件

傳智掃地僧課程學習筆記。include using namespace std class location copy建構函式 完成物件的初始化 location const location obj copy建構函式 location int getx int gety private int x...

c 學習4 賦值建構函式

1.賦值建構函式是將乙個引數物件中私有成員賦給乙個已經在記憶體中佔據記憶體的物件的私有成員,賦值建構函式被賦值的物件必須已經在記憶體中,否則呼叫的將是拷貝建構函式,當然賦值建構函式也有深拷貝和淺拷貝的問題。當然賦值建構函式必須能夠處理自我賦值的問題,因為自我賦值會出現指標指向乙個已經釋放的記憶體。還...