實(shí)際上,當(dāng)我們定義一個(gè)class而沒有明確定義構(gòu)造函數(shù)的時(shí)候,
編譯器會(huì)自動(dòng)假設(shè)兩個(gè)重載的構(gòu)造函數(shù)
(默認(rèn)構(gòu)造函數(shù)"default constructor" 和復(fù)制構(gòu)造函數(shù)"copy constructor")。
例如,對以下class:
class CExample {
public:
int a,b,c;
void multiply (int n, int m) { a=n; b=m; c=a*b; };
};
沒有定義構(gòu)造函數(shù),
編譯器自動(dòng)假設(shè)它有以下constructor 成員函數(shù):
- Empty constructor
它是一個(gè)沒有任何參數(shù)的構(gòu)造函數(shù),被定義為nop (沒有語句)。它什么都不做。
CExample::CExample () { };
-
- Copy constructor
它是一個(gè)只有一個(gè)參數(shù)的構(gòu)造函數(shù),該參數(shù)是這個(gè)class的一個(gè)對象,這個(gè)函數(shù)的功能是將被傳入的對象(object)的所有非靜態(tài)(non-static)成員變量的值都復(fù)制給自身這個(gè)object。
CExample::CExample (const CExample& rv) {
a=rv.a; b=rv.b; c=rv.c;
}
必須注意:這兩個(gè)默認(rèn)構(gòu)造函數(shù)(empty construction 和 copy constructor )
只有在沒有其它構(gòu)造函數(shù)被明確定義的情況下才存在。
如果任何其它有任意參數(shù)的構(gòu)造函數(shù)被定義了,這兩個(gè)構(gòu)造函數(shù)就都不存在了。
在這種情況下,
如果你想要有empty construction 和 copy constructor ,
就必需要自己定義它們。