Where should default parameters be specified?
At my workplace, usually default parameters are specified in the declaration.What is the normal custom? Should I specify default parameters in metho开发者_高级运维d declaration or method definition?
EDIT: Is there any way to specify default parameters for references?
EDIT: Can someone please provide an example of default arguments for reference parameters?
Method declaration. The caller probably doesn't have the definition, but default parameters must be known at the call place.
ybungalobill has already answered the question about where.
Regarding references, for a reference to const
T you can just specify a default value directly.
For a reference to non-const
you need to specify the default "value" as a reference to non-const
. This might be a global, or an instance of a class with suitable conversion. E.g.,
#include <iostream>
struct DummyInt
{
int dummy;
operator int& () { return dummy; }
DummyInt(): dummy( 0 ) {}
};
void foo( int& v = DummyInt() ) {} // Whatever
int main()
{
int x = 42;
foo( x );
foo();
}
Cheers & hth.,
– Alf
Well, the normal practice is to have the same set of default arguments for all translation units. In order to achieve that you obviously have to specify the default arguments in the declaration of the function in the header file.
As for default argument of reference parameter... of course, it is possible. For example
extern int i;
void foo(int &r = i);
void bar(const double &r = 0);
Must be at method declaration, so that the caller can know what is exactly expected by the function.
You can do tricks like Alf says but not sure why is it needed. May be you want to take a look at your design of function.
I used to make use of default values, but meanwhile I changed my mind: I find the code better readable when I write the parameter values explictly. Sometimes I define another method like the following:
bool Initialize( const char * pszPath );
bool InitializeDefault();
instead of
bool Initialize( const char * pszOptPath = NULL );
精彩评论