欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談c++構(gòu)造函數(shù)問(wèn)題,初始化和賦值問(wèn)題

 更新時(shí)間:2016年12月31日 09:19:46   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇淺談c++構(gòu)造函數(shù)問(wèn)題,初始化和賦值問(wèn)題。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

默認(rèn)構(gòu)造函數(shù)(就是沒(méi)有參數(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、由編譯器自動(dòng)生成

2、由我們自己定義的

這里又有兩種情況

上面說(shuō)了啊,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();

有一點(diǎn)注意的時(shí)候兩者不能同時(shí)使用:

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:這個(gè)指的是調(diào)用的時(shí)候不帶參數(shù)。

編譯器自動(dòng)添加默認(rèn)構(gòu)造函數(shù)的條件:編譯器實(shí)現(xiàn)的構(gòu)造函數(shù)其實(shí)就是什么都不做

1.沒(méi)有任何自己定義的構(gòu)造函數(shù)(即便是復(fù)制構(gòu)造函數(shù)也不行,如果自己定義復(fù)制構(gòu)造函數(shù),則必須自己定義構(gòu)造函數(shù))

2、數(shù)據(jù)成員中沒(méi)有const和reference。--因?yàn)橐跏蓟?/p>

拷貝構(gòu)造函數(shù)的參數(shù)必須是引用的原因:拷貝構(gòu)造函數(shù)的參數(shù)使用引用類型不是為了減少一次內(nèi)存拷貝, 而是避免拷貝構(gòu)造函數(shù)無(wú)限制的遞歸下去。

如果是值的話,那在傳值的時(shí)候還要再調(diào)一次拷貝構(gòu)造函數(shù)

然后又要傳值,又要再調(diào)一次....
然后你就內(nèi)存不夠,當(dāng)了

關(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;//其實(shí)就調(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的時(shí)候構(gòu)造臨時(shí)對(duì)象一次

如果函數(shù)返回對(duì)象,而不是指針,那么在執(zhí)行return的時(shí)候,會(huì)使用被return的對(duì)象“復(fù)制構(gòu)造”臨時(shí)對(duì)象,然后,return語(yǔ)句執(zhí)行完畢(遇到分號(hào);了)函數(shù)內(nèi)部創(chuàng)建的全部變量析構(gòu)、出棧。而被“賦值構(gòu)造”的臨時(shí)對(duì)象則在調(diào)用該函數(shù)的語(yǔ)句執(zhí)行完畢(遇到分號(hào);或者右邊的大括號(hào)})后,析構(gòu)。

總結(jié)一句:

臨時(shí)變量的生存范圍是語(yǔ)句級(jí)——分號(hào);結(jié)束或者右邊的大括號(hào)}結(jié)束。語(yǔ)句結(jié)束之后,臨時(shí)變量就被析構(gòu)了~

以上就是小編為大家?guī)?lái)的淺談c++構(gòu)造函數(shù)問(wèn)題,初始化和賦值問(wèn)題全部?jī)?nèi)容了,希望大家多多支持腳本之家~

相關(guān)文章

最新評(píng)論