簡體   English   中英

使用默認參數重載構造函數

[英]Overloading constructors with default parameters

我有一個包含5個變量的類:2個字符串,2個雙精度數和1個int。

用戶將始終能夠提供至少一個字符串和一個double,但可能無法提供其余信息,這意味着應包含默認參數。

當然,嘗試使用所有參數創建一堆構造函數不起作用 - 它無法編譯。

說我嘗試這樣的事情:

         Object(std::string s1, double d1) {
            this->string1 = s1;
            this->double1 = d1;
            this->int1 = 0;
            this->double2 = 0.0;
            this->string2 = "foo";
    }
         Object(std::string s1, double d1, int i) {
            this->string1 = s1;
            this->double1 = d1;
            this->int1 = i;
            this->double2 = 0.0;
            this->string2 = "foo";
    }

    // and so on...

這會重載構造函數,但這些仍然被認為是默認參數嗎?

有沒有辦法在每個構造函數中包含默認參數的每個參數? 即,類似於這種不起作用的東西:

 Object(std::string s1, double d1, int i = 0, std::string s2 = "foo", double d2 = 0.0) {

 ...
 }
 Object(std::string s1, double d1, int i, std::string s2 = "foo", double d2 = 0.0) {

 ...
 }
 // and so on...

這個問題是,如果用戶只需要5個值中的4個,那么在某些時候它必須“跳過”一個參數。 例如,如果我剛剛使用了第一個字符串,並且用戶沒有第二個字符串,那么就沒有辦法通過它來傳遞第二個字符串。

對於具有那么多構造參數的類,我建議你使用構建器模式 這種模式基本上使用一個單獨的構建器類來保存所有構造參數,然后將它們全部傳遞給真實類的構造函數。

使用構建器模式,您可以在構建器中建立默認參數值,因此如果只需要覆蓋一個或兩個參數,則調用代碼仍然可以保持簡單。

(如果您在問題中使用了真實的類和參數名稱,我可以編寫一個示例構建器來演示這一點,但希望閱讀構建器模式可以讓您有一個想法。)

默認參數值在參數列表(而不是函數體)中指定,如第二個代碼示例中所示。

你需要的只是身體

Object(std::string s1, double d1, int i = 0, std::string s2 = "foo", double d2 = 0.0)
{
            this->string1 = s1;
            this->double1 = d1;
            this->int1 = i;
            this->double2 = s2;
            this->string2 = d2;
}

雖然,正確的C ++語法是使用初始化列表:

Object(std::string s1, double d1, int i = 0, std::string s2 = "foo", double d2 = 0.0):
    string1( s1 ),
    double1( d1 ),
    int1( i ),
    double2( s2 ),
    string2( d2 )
{
    // constructor body
}

當用戶使用s1和d1或者指定的i,s2和d2調用構造函數時,將填充默認值。唯一需要注意的是它們必須按順序提供。 你不能只提供i和d2,你只能提供i和s2,或i,s2和d2。

Object myobject ( "s1", 0.5 );    //valid
Object myobject ( "s1", 0.5, 9, "foo" ); //valid
Object myobject ( "s1", 0.5, "s2" ); //invalid, skipped parameter 'i'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM