如何为 C++ 构造函数指定默认参数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3393824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I specify default argument values for a C++ constructor?
提问by boom
I have a constructor declaration as:
我有一个构造函数声明为:
MyConstuctor(int inDenominator, int inNumerator);
and definition as
和定义为
MyConstuctor::MyConstuctor(int inDenominator,
int inNumerator, int inWholeNumber = 0)
{
mNum = inNumerator;
mDen = inDenominator;
mWhole = inWholeNumber;
}
but i want to have an option of passing whole number as third parameter depending on caller object. is this the right way. if not what can be the alternative way.
但我希望可以选择根据调用者对象将整数作为第三个参数传递。这是正确的方法吗?如果不是什么可以是替代方式。
回答by Igor Oks
What you need is:
你需要的是:
//declaration:
MyConstuctor(int inDenominator, int inNumerator, int inWholeNumber = 0);
//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber)
{
mNum = inNumerator;
mDen = inDenominator;
mWhole = inWholeNumber;
}
This way you will be able to provide a non-default value for inWholeNumber
; and you will be able not to provide it so 0 will be used as the default.
这样你就可以为inWholeNumber
;提供一个非默认值。并且您将无法提供它,因此将使用 0 作为默认值。
As an additional tip, better use initialization listin the definition:
作为附加提示,最好在定义中使用初始化列表:
//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber) :
mNum(inNumerator), mDen(inDenominator), mWhole (inWholeNumber)
{
}
回答by Naveen
No, you need to provide the default value in the declaration of the method only. The definition of the method should have all 3 parameters without the default value. If the user of the class chooses to pass the 3rd parameter it will be used, otherwise default value specified in the declaration will be used.
不,您只需要在方法的声明中提供默认值。方法的定义应该包含所有 3 个参数,没有默认值。如果类的用户选择传递第三个参数,它将被使用,否则将使用声明中指定的默认值。
回答by dst
You should add the default parameter to the declaration as well and the default value in the implementation is not necessary.
您还应该将默认参数添加到声明中,并且实现中的默认值不是必需的。