2013-05-25 47 views

回答

4

使用默認參數,與參數只能有默認值由右至左讀,所以沒有違約y違約x的限制是不是一種選擇:

A(int x, int y = 0) {} 

你的其他選擇是使超載:

A(int x, int y) {} 
A(int x) {/*use 0 instead of y*/} 

第二可與委派構造用於更復雜的組合工作特別好

A(int x, int y) {/*do main work*/} 
A(int x) : A(x, 0) {/*this is run after the other constructor*/} 

但是,只要您執行了其中的任何操作,請注意隱式轉換爲您的類更容易。而不是唯一可能的{6, 10},您已獲得通過5作爲A的可能性。在允許這些隱式轉換之前先仔細想想,直到您知道您需要它們,請在構造函數簽名前面粘貼explicit以禁用它們。

+0

'explicit'如何? –

+0

@CaptainObvlious,這取決於隱式轉換是否合意。但是,在大多數情況下,放入'explicit'是個好主意,但是如果有疑問,稍後刪除比稍後添加更容易。 – chris

+0

我只是認爲這將是一個很好的補充答案;) –

1

如果您想將默認值傳遞給參數,您可以在構造函數聲明中指定它。

class A 
{ 
    A(int x, int y = 0) 
    { 
    } 
}; 

int main() 
{ 
    A(4); 
} 

爲構造函數聲明默認參數時要小心。如果沒有聲明explicit,任何可以使用單個參數調用的構造函數都可以調用隱式轉換。

A(int x = 0, int y = 0) // <-- can invoke implicit conversion 
A(int x, int y = 0)  // <-- can invoke implicit conversion 
A(int x, int y)   // <-- does NOT implicit conversion 

爲了防止隱式轉換,從存在的聲明構造爲explicit

explicit A(int x = 0, int y = 0) // <-- No longer invokes implicit conversion 
explicit A(int x, int y = 0)  // <-- No longer invokes conversion 
A(int x, int y)     // <-- does not require explicit keyword 
0

你必須給默認變量,這樣的構造變得

A(int x=5, int y=4) 

} 

Y的默認值變爲4 x默認爲5

相關問題