定義一個class而沒有明確定義構(gòu)造函數(shù)的時候,編譯器會自動假設兩個重載的構(gòu)造函數(shù)
實際上,當我們定義一個class而沒有明確定義構(gòu)造函數(shù)的時候,
編譯器會自動假設兩個重載的構(gòu)造函數(shù)
(默認構(gòu)造函數(shù)"default constructor" 和復制構(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ù),
編譯器自動假設它有以下constructor 成員函數(shù):
- Empty constructor
它是一個沒有任何參數(shù)的構(gòu)造函數(shù),被定義為nop (沒有語句)。它什么都不做。
CExample::CExample () { };
-
- Copy constructor
它是一個只有一個參數(shù)的構(gòu)造函數(shù),該參數(shù)是這個class的一個對象,這個函數(shù)的功能是將被傳入的對象(object)的所有非靜態(tài)(non-static)成員變量的值都復制給自身這個object。
CExample::CExample (const CExample& rv) {
a=rv.a; b=rv.b; c=rv.c;
}
必須注意:這兩個默認構(gòu)造函數(shù)(empty construction 和 copy constructor )
只有在沒有其它構(gòu)造函數(shù)被明確定義的情況下才存在。
如果任何其它有任意參數(shù)的構(gòu)造函數(shù)被定義了,這兩個構(gòu)造函數(shù)就都不存在了。
在這種情況下,
如果你想要有empty construction 和 copy constructor ,
就必需要自己定義它們。
posted on 2008-12-04 18:04 henry08 閱讀(2118) 評論(5) 編輯 收藏 引用 所屬分類: C++