Using one of the parameter's getter to set the value of another parameter in a C++ function?
In a C++ function, can I use one of the parameter's getter to set the default value of the other parameter following it? For example if I have the followig class Foo,
class Foo{
public:
setID();
getID();
private:
string id;
}
Can I write a function fooManipulator li开发者_运维问答ke this,
int fooManipulator(Foo bar, string id = bar.getId());
No, as has been stated, the order of evaluation of arguments to a function is unspecified.
However, you can achieve the effect easily with an overload like this:
int fooManipulator(Foo bar)
{
return fooManipulator(bar, bar.getId());
}
No. You cannot refer to another parameter in a default argument because the order of evaluation of function arguments is unspecified.
For example, in your fooManipulator
function, the argument passed to parameter id
may be evaluated before the argument passed to parameter bar
. This could make invalid the use of bar
in the default argument for parameter id
.
精彩评论