拷貝構(gòu)造函數(shù)是C++最基礎(chǔ)的概念之一,大家自認為對拷貝構(gòu)造函數(shù)了解么?請大家先回答一下三個問題:
1. 以下函數(shù)哪個是拷貝構(gòu)造函數(shù),為什么?
X::X(const X&);??
X::X(X);??
X::X(X&, int a=1);??
X::X(X&, int a=1, b=2);?
2. 一個類中可以存在多于一個的拷貝構(gòu)造函數(shù)嗎?
3. 寫出以下程序段的輸出結(jié)果, 并說明為什么? 如果你都能回答無誤的話,那么你已經(jīng)對拷貝構(gòu)造函數(shù)有了相當(dāng)?shù)牧私狻?/font>
?
#include
#include
struct X {??
? template
? X( T& ) { std::cout << "This is ctor." << std::endl; }??
? template
??? X& operator=( T& ) { std::cout << "This is ctor." << std::endl; }??
};??
void main() {??
? X a(5);??
? X b(10.5);??
? X c = a;??
? c = b;??
}?
解答如下:
1. 對于一個類X,如果一個構(gòu)造函數(shù)的第一個參數(shù)是下列之一:
??? a) X&
??? b) const X&
??? c) volatile X&
??? d) const volatile X&
??? 且沒有其他參數(shù)或其他參數(shù)都有默認值,那么這個函數(shù)是拷貝構(gòu)造函數(shù).
??? X::X(const X&);? //是拷貝構(gòu)造函數(shù)??
??? X::X(X&, int=1); //是拷貝構(gòu)造函數(shù)?
??? X::X(X&, int a=1, b=2);? //是拷貝構(gòu)造函數(shù)?
2.類中可以存在超過一個拷貝構(gòu)造函數(shù),
class X {?????
public:?????
? X(const X&);?????
? X(X&);??????????? // OK??
};?
注意,如果一個類中只存在一個參數(shù)為X&的拷貝構(gòu)造函數(shù),那么就不能使用const X或volatile X的對象實行拷貝初始化.
class X {??
public:??
? X();??
? X(X&);??
};??
const X cx;??
X x = cx;??? // error??
如果一個類中沒有定義拷貝構(gòu)造函數(shù),那么編譯器會自動產(chǎn)生一個默認的拷貝構(gòu)造函數(shù).這個默認的參數(shù)可能為X::X(const X&)或X::X(X&),由編譯器根據(jù)上下文決定選擇哪一個.
默認拷貝構(gòu)造函數(shù)的行為如下:默認的拷貝構(gòu)造函數(shù)執(zhí)行的順序與其他用戶定義的構(gòu)造函數(shù)相同,執(zhí)行先父類后子類的構(gòu)造.拷貝構(gòu)造函數(shù)對類中每一個數(shù)據(jù)成員執(zhí)行成員拷貝(memberwise Copy)的動作.
?a)如果數(shù)據(jù)成員為某一個類的實例,那么調(diào)用此類的拷貝構(gòu)造函數(shù).
?b)如果數(shù)據(jù)成員是一個數(shù)組,對數(shù)組的每一個執(zhí)行按位拷貝.
?c)如果數(shù)據(jù)成員是一個數(shù)量,如int,double,那么調(diào)用系統(tǒng)內(nèi)建的賦值運算符對其進行賦值.
3.? 拷貝構(gòu)造函數(shù)不能由成員函數(shù)模版生成.
struct X {??
??? template
??? X( const T& );??? // NOT copy ctor, T can't be X??
??? template
??? operator=( const T& );? // NOT copy ass't, T can't be X??
};??
原因很簡單,成員函數(shù)模版并不改變語言的規(guī)則,而語言的規(guī)則說,如果程序需要一個拷貝構(gòu)造函數(shù)而你沒有聲明它,那么編譯器會為你自動生成一個. 所以成員函數(shù)模版并不會阻止編譯器生成拷貝構(gòu)造函數(shù), 賦值運算符重載也遵循同樣的規(guī)則
新聞熱點
疑難解答