默認構(gòu)造函數(shù)(就是沒有參數(shù)的構(gòu)造函數(shù))
The Default Constructor
The default constructor is the constructor used to create an object when you don't provide explicit initialization values. That is, it's the constructor used for declarations like this:
Stock stock1; // uses the default constructor
1、由編譯器自動生成
2、由我們自己定義的
這里又有兩種情況
上面說了啊,default constructor有兩種(……your own default constructor. This is a constructor that takes no arguments):
1)One is to provide default values for all the arguments to the existing constructor:
Stock(const char * co = "Error", int n = 0, double pr = 0.0);
2)The second is to use function overloading to define a second constructor, one that has no arguments:
Stock();
有一點注意的時候兩者不能同時使用:
You can have only one default constructor, so be sure that you don't do both. (With early versions of C++, you could use only the second method for creating a default constructor.)
This is a constructor that takes no arguments:這個指的是調(diào)用的時候不帶參數(shù)。
編譯器自動添加默認構(gòu)造函數(shù)的條件:編譯器實現(xiàn)的構(gòu)造函數(shù)其實就是什么都不做
1.沒有任何自己定義的構(gòu)造函數(shù)(即便是復(fù)制構(gòu)造函數(shù)也不行,如果自己定義復(fù)制構(gòu)造函數(shù),則必須自己定義構(gòu)造函數(shù))
2、數(shù)據(jù)成員中沒有const和reference。--因為要初始化。
拷貝構(gòu)造函數(shù)的參數(shù)必須是引用的原因:拷貝構(gòu)造函數(shù)的參數(shù)使用引用類型不是為了減少一次內(nèi)存拷貝, 而是避免拷貝構(gòu)造函數(shù)無限制的遞歸下去。
如果是值的話,那在傳值的時候還要再調(diào)一次拷貝構(gòu)造函數(shù)
然后又要傳值,又要再調(diào)一次....
然后你就內(nèi)存不夠,當了
關(guān)于賦值==函數(shù)和拷貝構(gòu)造函數(shù)的區(qū)別:
#include<iostream>using namespace std;class A{ public:int i;A( const A& a){ i=a.i;cout<<"copy is build"<<endl;}explicit A(int y){ i=y;}};A fun(A i){ A a1(i); A a2=a1;//其實就調(diào)用拷貝構(gòu)造函數(shù)return a2;}int main(){ A a(1);fun(a); }拷貝構(gòu)造函數(shù)一共調(diào)用四次拷貝構(gòu)造函數(shù)。。fun參數(shù)傳值一次,a1(i)一次,a2(a1)一次,return的時候構(gòu)造臨時對象一次
如果函數(shù)返回對象,而不是指針,那么在執(zhí)行return的時候,會使用被return的對象“復(fù)制構(gòu)造”臨時對象,然后,return語句執(zhí)行完畢(遇到分號;了)函數(shù)內(nèi)部創(chuàng)建的全部變量析構(gòu)、出棧。而被“賦值構(gòu)造”的臨時對象則在調(diào)用該函數(shù)的語句執(zhí)行完畢(遇到分號;或者右邊的大括號})后,析構(gòu)。
總結(jié)一句:
臨時變量的生存范圍是語句級――分號;結(jié)束或者右邊的大括號}結(jié)束。語句結(jié)束之后,臨時變量就被析構(gòu)了~
以上就是小編為大家?guī)淼臏\談c++構(gòu)造函數(shù)問題,初始化和賦值問題全部內(nèi)容了,希望大家多多支持武林網(wǎng)~
新聞熱點
疑難解答