我該如何做到這一點,如果沒有參數提供給構造函數,默認值賦予變量?如何給變量一個默認值,如果沒有參數提供給構造函數? C++
例如:
class A {
A(int x, int y)
}
int main() {
A(4);
}
在該例子中,我沒有通過一個值,Y,我怎麼會做這麼y具有0例如默認值,因爲沒有參數,其中供應嗎?
我該如何做到這一點,如果沒有參數提供給構造函數,默認值賦予變量?如何給變量一個默認值,如果沒有參數提供給構造函數? C++
例如:
class A {
A(int x, int y)
}
int main() {
A(4);
}
在該例子中,我沒有通過一個值,Y,我怎麼會做這麼y具有0例如默認值,因爲沒有參數,其中供應嗎?
使用默認參數,與參數只能有默認值由右至左讀,所以沒有違約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
以禁用它們。
如果您想將默認值傳遞給參數,您可以在構造函數聲明中指定它。
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
你必須給默認變量,這樣的構造變得
A(int x=5, int y=4)
}
Y的默認值變爲4 x默認爲5
'explicit'如何? –
@CaptainObvlious,這取決於隱式轉換是否合意。但是,在大多數情況下,放入'explicit'是個好主意,但是如果有疑問,稍後刪除比稍後添加更容易。 – chris
我只是認爲這將是一個很好的補充答案;) –