Possible Duplicate:
Default value to a parameter while passing by reference in C++
Is it possible to do something like this:
// definition
bool MyFun(int n开发者_Go百科MyInt, char* szMyChar, double& nMyReferencedDouble = 0.0);
Then the function can be called either like this:
MyFun(nMyInt, szMyChar, nMyReferencedDouble);
or like this:
MyFun(nMyInt, szMyChar);
My compiler (VS 98) complains. Is there a way to do this?
As you can only bind temporary objects to a const
reference and constant expression default arguments convert to temporary objects, you can only do this with a parameter that is a const
reference.
You can, however, overload the function and have the one which doesn't take a reference create a local named object and pass that to the overload that does take an extra reference parameter.
Actually, what I've said isn't strictly true. Default arguments are like initializers for parameters so if you had a suitable non-const double available, you could bind that to the reference parameter.
e.g.
extern double dflt;
bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble = dflt);
You could overload the function instead.
// Definition
bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble);
// Overload
bool MyFun(int nMyInt, char* szMyChar)
{
double nMyReferencedDouble = 0.0;
MyFun( nMyInt, szMyChar, nMyReferencedDouble );
}
This is how you get around the current limitations of no default values in C# and works equally well for semantic limitations in C++.
It is not allowed, because you have a non-const reference. It is possible if you would have a const reference
bool MyFun(int nMyInt, char* szMyChar, const double& nMyReferencedDouble = 0.0)
but I presume that this is not what you need.
No it is not. Basically, reference is something that should be existing. In your case, if you don't pass a variable for the fun() then nMyReferencedDouble would not refer to any thing.
精彩评论