Home > Article > Backend Development > How Can You Use Member Variables as Default Arguments in C Member Functions?
Using Member Variables as Default Arguments in C
In C , you may encounter the need to make arguments for member functions optional. When no argument is provided, it would be preferable to use a member variable as the default.
Consider the following example:
class Object { ... void MoveTo(double speed, Point position); protected: Point initPos; Point currPos; };
The code attempts to assign the member variable initPos as the default value for the position parameter in the MoveTo function:
void Object::MoveTo(double speed, Point position = initPos) { currPos = postion; }
However, this approach results in a compilation error:
error: invalid use of non-static data member 'Object::initPos'
The issue is that default argument expressions for member functions must rely solely on class or global scope elements. Additionally, the default argument must be defined in the method's declaration in the header file.
To resolve this, two overloads of the MoveTo method can be created:
void Object::MoveTo(double speed) { MoveTo(speed, initPos); } void Object::MoveTo(double speed, Point position) { // Implementation here. }
The MoveTo method that takes a single argument calls the MoveTo method with two arguments, passing the initPos value as the default.
Object object; object.MoveTo(10.0); // Calls MoveTo(10.0, initPos)
This approach adheres to the DRY principle by allowing the implementation of MoveTo to be defined only once.
The above is the detailed content of How Can You Use Member Variables as Default Arguments in C Member Functions?. For more information, please follow other related articles on the PHP Chinese website!