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

C++之構(gòu)造函數(shù)默認(rèn)值設(shè)置方式

 更新時(shí)間:2023年08月09日 10:09:00   作者:ClassRoom706  
這篇文章主要介紹了C++之構(gòu)造函數(shù)默認(rèn)值設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

C++構(gòu)造函數(shù)默認(rèn)值設(shè)置

構(gòu)造函數(shù)默認(rèn)值

C++類中構(gòu)造函數(shù)設(shè)置默認(rèn)值應(yīng)當(dāng)注意:

  • C++類構(gòu)造函數(shù)只能對(duì)排在最后的參數(shù)提供默認(rèn)值;
  • 既可以在構(gòu)造函數(shù)的聲明中,也可以在構(gòu)造函數(shù)的實(shí)現(xiàn)中,提供缺省值,但,不能在兩者同時(shí)提供缺省默認(rèn)值。

代碼:

#include <iostream>
using namespace std;
class CTest
{
public: ? ?
? ? CTest();
? ? CTest(int _a, double _b, const bool _c = false, bool _d = true);
private:
? ? const bool c;
? ? bool d;
? ? int a;
? ? double b;?
};
CTest::CTest(int _a, double _b = 1.0, const bool _c, ?bool _d):a(_a), b(_b), c(_c), d(_d)
{
? ? cout << a << endl;
? ? cout << b << endl;
? ? cout << c << endl;
? ? cout << d << endl; ?
}
int main()
{
? ? // CTest* test = new CTest(1, 1.0, true, false);
? ? // CTest* test = new CTest(1, 1.0, true);
? ? //CTest* test = new CTest(1, 1.0);
? ? CTest* test = new CTest(1);
? ? return 0;
}

C++構(gòu)造函數(shù)默認(rèn)參數(shù)使用

一 代碼

#include <iostream>
using namespace std;
class Box{
public:
    Box(int h=2,int w=2,int l=2);//在聲明構(gòu)造函數(shù)時(shí)指定默認(rèn)參數(shù)
    int volume();
private:
    int height,width,length;
};
Box::Box(int h,int w,int len){//在定義函數(shù)時(shí)可以不指定默認(rèn)參數(shù)
    height=h;
    width=w;
    length=len;
}
int Box::volume(){
    return height*width*length;
}
int main(){
    Box box1(1);//不指定第2、3個(gè)實(shí)參
    cout<<"box1's volume: "<<box1.volume()<<endl;
    Box box2(1,3);// 不指定第3個(gè)實(shí)參
    cout<<"box2's volume: "<<box2.volume()<<endl;
    Box box3;
    cout<<"box3's volume:"<<box3.volume()<<endl;
    return 0;
}

二 運(yùn)行

[root@localhost charpter02]# ./0210
box1's volume: 4
box2's volume: 6
box3's volume:8

三 說明

該實(shí)戰(zhàn)中,定義了一個(gè)帶默認(rèn)參數(shù)的構(gòu)造函數(shù),是在聲明時(shí)指定默認(rèn)參數(shù),而定義時(shí)則可以不指定默認(rèn)參數(shù)。定義對(duì)象時(shí),可以傳0~3個(gè)參數(shù),傳了幾個(gè)參數(shù),就替換前面的幾個(gè)參數(shù),其余都使用默認(rèn)參數(shù)。

使用默認(rèn)參數(shù)的好處在于:調(diào)用構(gòu)造函數(shù)時(shí)就算沒有提供參數(shù)也不會(huì)出錯(cuò),且對(duì)每一個(gè)對(duì)象能有相同的初始化狀態(tài)。

不過,應(yīng)該在聲明構(gòu)造函數(shù)默認(rèn)值時(shí)指定默認(rèn)參數(shù)值,而不能只在定義構(gòu)造函數(shù)時(shí)指定默認(rèn)參數(shù)值。如果構(gòu)造函數(shù)中的參數(shù)全指定了默認(rèn)值,則在定義對(duì)象時(shí),可給一個(gè)實(shí)參或多個(gè)實(shí)參,也可不給實(shí)參。

一個(gè)類中如果定義了全是默認(rèn)參數(shù)的構(gòu)造函數(shù)后,就不能再定義重載構(gòu)造函數(shù)了。

假設(shè)Box類中定義了3個(gè)構(gòu)造函數(shù)

Box(int =10,int=3,int=5);
Box();
Box(int,int);

若有以下定義語(yǔ)句,則會(huì)出現(xiàn)問題

Box box1;              //是應(yīng)該調(diào)用第1個(gè)構(gòu)造函數(shù)還是應(yīng)該調(diào)用第2個(gè)構(gòu)造函數(shù)
Box box2(13,18);        //是應(yīng)該調(diào)用第2個(gè)構(gòu)造函數(shù)還是應(yīng)該調(diào)用第3個(gè)構(gòu)造函數(shù)

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論