欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊: 次

默認(rèn)構(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、由編譯器自動(dòng)生成

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();

有一點(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.沒有任何自己定義的構(gòu)造函數(shù)(即便是復(fù)制構(gòu)造函數(shù)也不行,如果自己定義復(fù)制構(gòu)造函數(shù),則必須自己定義構(gòu)造函數(shù))

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

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

如果是值的話,那在傳值的時(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í)對象一次

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

總結(jié)一句:

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

以上就是小編為大家?guī)淼臏\談c++構(gòu)造函數(shù)問題,初始化和賦值問題全部內(nèi)容了,希望大家多多支持我們~

上一篇:利用反射獲得類的public static/const成員的值實(shí)例

欄    目:C語言

下一篇:C/C++ 讀取16進(jìn)制文件的方法

本文標(biāo)題:淺談c++構(gòu)造函數(shù)問題,初始化和賦值問題

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/1862.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有