淺談c++構造函數(shù)問題,初始化和賦值問題
默認構造函數(shù)(就是沒有參數(shù)的構造函數(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ù)。
編譯器自動添加默認構造函數(shù)的條件:編譯器實現(xiàn)的構造函數(shù)其實就是什么都不做
1.沒有任何自己定義的構造函數(shù)(即便是復制構造函數(shù)也不行,如果自己定義復制構造函數(shù),則必須自己定義構造函數(shù))
2、數(shù)據(jù)成員中沒有const和reference。--因為要初始化。
拷貝構造函數(shù)的參數(shù)必須是引用的原因:拷貝構造函數(shù)的參數(shù)使用引用類型不是為了減少一次內(nèi)存拷貝, 而是避免拷貝構造函數(shù)無限制的遞歸下去。
如果是值的話,那在傳值的時候還要再調(diào)一次拷貝構造函數(shù)
然后又要傳值,又要再調(diào)一次....
然后你就內(nèi)存不夠,當了
關于賦值==函數(shù)和拷貝構造函數(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)用拷貝構造函數(shù) return a2; } int main() { A a(1); fun(a); }
拷貝構造函數(shù)一共調(diào)用四次拷貝構造函數(shù)。。fun參數(shù)傳值一次,a1(i)一次,a2(a1)一次,return的時候構造臨時對象一次
如果函數(shù)返回對象,而不是指針,那么在執(zhí)行return的時候,會使用被return的對象“復制構造”臨時對象,然后,return語句執(zhí)行完畢(遇到分號;了)函數(shù)內(nèi)部創(chuàng)建的全部變量析構、出棧。而被“賦值構造”的臨時對象則在調(diào)用該函數(shù)的語句執(zhí)行完畢(遇到分號;或者右邊的大括號})后,析構。
總結一句:
臨時變量的生存范圍是語句級——分號;結束或者右邊的大括號}結束。語句結束之后,臨時變量就被析構了~
以上就是小編為大家?guī)淼臏\談c++構造函數(shù)問題,初始化和賦值問題全部內(nèi)容了,希望大家多多支持腳本之家~
相關文章
C語言數(shù)組實現(xiàn)公交車管理系統(tǒng)
這篇文章主要介紹了C語言數(shù)組實現(xiàn)公交車管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-12-12使用C語言遞歸與非遞歸實現(xiàn)字符串反轉函數(shù)char *reverse(char *str)的方法
本篇文章是對使用C語言遞歸與非遞歸實現(xiàn)字符串反轉函數(shù)char *reverse(char *str)進行了詳細的分析介紹,需要的朋友參考下2013-05-05