C 中的拷貝構造 賦值建構函式

2022-05-21 02:01:16 字數 1694 閱讀 5385

c++中的拷貝構造,賦值構造的形式如下:

eg:

a (a &a) 

a(const a &a)

a &operator = (const a &a)

物件以值傳遞方式從函式返回時,若接受返回值的物件已經初始化過,則會呼叫賦值建構函式,且該物件還會呼叫析構函式,當物件中包含指標時,會使該指標失效,因此需要過載賦值建構函式,使用類似深拷貝或移動建構函式的方法賦值,才能避免指標失效。

#includeusing namespace std;

class a

a(const a &a)

a &operator = (const a &a)

a (int t)

~a()

};void func(a ret)

a get()

int main()

測試結果

address: 89fed0, point:fb1698, val: 1

這是乙個拷貝建構函式

c的:global address: 89fed8, point: fb1698, value: 1

這是乙個拷貝建構函式

傳值:stack address: 89fee0, point: fb1698, value: 1

delete 89fee0

address: 89fee8, point:fb1798, val: 3

從函式返回時stack address: 89fee8, point: fb1798, value: 3

d的:global address: 89fee8, point: fb1798, value: 3

delete 89fee8

delete 89fed8

delete 89fed0

#includeusing namespace std;

class a

a &operator = (const a &a)

a (int t)

~a()

};void func(a ret)

a f ()

int main()

測試結果

address: 89fee8, point:f51788, val: 3

stack address: 89fee8, point: f51788, value: 3

這是乙個賦值建構函式

delete 89fee8

global address: 89fed8, point: f51788, value: 3

address: 89fee0, point:f51698, val: 1

global address: 89fee8, point: f51698, value: 1

delete 89fee8

delete 89fee0

delete 89fed8

形參進行值傳遞:

a( a);
不能。如果是這種情況下,呼叫拷貝建構函式的時候,首先要將實參傳遞給形參,這個傳遞的時候又要呼叫拷貝建構函式。。如此迴圈,無法完成拷貝,棧也會滿。(俗稱套娃)

C 建構函式例項 拷貝構造,賦值

define crt secure no warnings windows系統 include include include using namespace std class student student operator const student s student const stude...

建構函式 拷貝建構函式 賦值建構函式

class和struct很大乙個區別在於,c除了成員的訪問控制許可權,struct中的成員預設是public,而class中的field預設是private class還有乙個special的地方是它有建構函式 constructor。建構函式是class中的一員,和成員變數 其他成員函式一起構成乙...

建構函式 拷貝函式 賦值建構函式

ifndef sample h define sample h include include struct qq int qqnum std string qqpassword 以下a,b,c,d分別為 a 沒有實現拷貝建構函式和賦值建構函式,所以會自動生成預設的拷貝建構函式和賦值建構函式 b 與...