C 拷貝控制 學習筆記

2021-10-23 01:57:29 字數 2084 閱讀 2037

sales_data::

sales_data

(const sales_data &orig)

:bookno

(orig.bookno)

,units_sold

(orig.units_sold)

,revenue

(orig.revenue)

string dots(10

,'.');

// 直接初始化

string s

(dots)

;// 直接初始化

string s2 = dots;

//拷貝初始化

string null_book =

"99999999"

;//拷貝初始化

string nines =

string

(100

,'9');

//拷貝初始化

拷貝建構函式的第乙個引數最好為const型別,因為拷貝建構函式並不會更改被拷貝物件。

sales_data& sales_data::

operator=(

const sales_data &rhs)

class

sales_data

;

class

string

;

//普通建構函式

string::

string

(const

char

*str)

else

}//拷貝建構函式

string::

string

(const string &other)

else

}//拷貝賦值運算子

string & string::

operator=(

const string &other)

//如果不是自賦值,就先釋放記憶體

delete

m_data;

int len=

strlen

(other.m_data)

; m_data=

newchar

[len+1]

;strcpy

(m_data, other.m_data)

;return

*this;}

//析構函式

string::

~string

(void

)

struct nocopy

;

class

hasptr

//普通建構函式

hasptr

(const hasptr&);

//拷貝建構函式

hasptr&

operator=(

const hasptr&);

//賦值運算子

~hasptr()

;//析構函式

private

: string *ps;

int i;

}

hasptr::

hasptr

(const hasptr ©)

也可以直接使用建構函式初始值列表:

hasptr::

hasptr

(const hasptr ©):i

(copy.i),ps

(new

string

(*copy.ps)

);

hasptr& hasptr::

operator=(

const hasptr &orig)

hasptr::

~hasptr()

C 學習筆記之 13 拷貝控制

本文將學習類如何通過一組函式控制物件拷貝 賦值 移動和銷毀,這組函式分別是拷貝建構函式 移動建構函式 拷貝賦值運算子 移動賦值運算子以及析構函式。若類沒有顯示定義這些拷貝控制成員,則編譯器會自動定義。如果乙個建構函式的第乙個引數是自身類型別的引用 幾乎總為const引用 且任何額外引數都有預設值,則...

C Primer學習筆記 13 拷貝控制

題記 本系列學習筆記 c primer學習筆記 主要目的是討論一些容易被大家忽略或者容易形成錯誤認識的內容。只適合於有了一定的c 基礎的讀者 至少學完一本c 教程 如果文中有錯誤或遺漏之處,敬請指出,謝謝!c 類中有四個不可或缺的部分,那就是建構函式 拷貝建構函式 賦值操作符和析構函式。如果類中沒有...

c 筆記 類型別拷貝控制

乙個類通過定義五種特殊的成員函式來控制物件的拷貝,移動,賦值和銷毀操作,分別是拷貝建構函式 拷貝賦值建構函式 移動建構函式 移動賦值運算子和析構函式。拷貝和移動建構函式定義了當同型別的另乙個物件初始化本物件時,做什麼操作 拷貝和移動賦值運算子定義了乙個物件賦值給同型別的另乙個物件時,做什麼操作 析構...