Using a Member Variable as Default Argument in C
In C , it's possible to specify a default argument for a member function using a member variable. However, attempting to use a member function as the default argument may result in a compiler error, as seen in the example below.
class Object { protected: Point initPos; Point currPos; void MoveTo(double speed, Point position = initPos); }; void Object::MoveTo(double speed, Point position) { currPos = postion; }
This code will encounter the following compilation error:
error: invalid use of non-static data member 'Object::initPos'
Reason for the Error
Default argument expressions in member functions are restricted to using elements within the class or at global scope. Here, the compiler cannot determine the value of the initPos member variable when the function is called, leading to the error.
Solution
To resolve this issue, use function overloading with the following approach:
// Single-argument overload that defaults to initPos void Object::MoveTo(double speed) { MoveTo(speed, initPos); } // Two-argument overload that takes the explicit position void Object::MoveTo(double speed, Point position) { // Implementation here }
Advantages
This technique allows for optional argument handling in member functions while maintaining implementation in a single method. It follows the DRY (Don't Repeat Yourself) principle by avoiding code duplication while providing a convenient way to specify default values.
The above is the detailed content of Why Can't a Member Variable Be Used as a Default Argument in a C Member Function?. For more information, please follow other related articles on the PHP Chinese website!