重载方法或使用默认值? c ++ [英] Overload a method or use default values? c++
问题描述
我还是相对较新的C + +,我似乎无法弄清楚下面两种方法的编码一个函数可能需要一个参数,或者可能两个或三个或更多。无论如何,这是我的观点
I'm still relatively new to C++ and I can't seem to figure out the difference in the following two ways of coding a function that may take one parameter or maybe two or three or more. Anyway, here's my point
函数重载:
int aClass::doSomething(int required)
{
//DO SOMETHING
}
int aClass::doSomething(int required, int optional)
{
//DO SOMETHING
}
与此不同的是,默认值:
how is this different to, default value:
int aClass::doSomething(int required, int optional = 0)
{
//DO SOMETHING
}
我知道在不同的情况下,一个可能比另一个更合适,
I know in different circumstances one may be more suitable than another but what kinds of things should I be aware of when choosing between each of these options?
推荐答案
首先,你在谈论 >重载,不覆盖。在导出类中为 virtual
函数覆盖。重载是指具有不同签名的相同函数名。
First off, you're talking about overloading, not overriding. Overriding is done for virtual
functions in a derived class. Overloading refers to the same function name with a different signature.
区别是逻辑的 - 在第一种情况下(两个版本),两个函数可以完全不同,第二种情况将具有或多或少相同的逻辑。这完全取决于你。
The difference is logical - in the first case (2 versions), the two functions can behave completely different, whereas the second case will have more or less the same logic. It's really up to you.
这篇关于重载方法或使用默认值? c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!