Using a Member Variable as a Default Argument in C
When crafting member functions in C , it's often desirable to make certain arguments optional and use a member variable as a default value. However, this can trigger compilation errors if the member variable is not static.
Consider the following code snippet:
class Object { public: void MoveTo(double speed, Point position); protected: Point initPos; Point currPos; }; void Object::MoveTo(double speed, Point position = initPos) { currPos = postion; }
Attempting to compile this code will result in the error message: "invalid use of non-static data member 'Object::initPos'". This occurs because default argument expressions cannot depend on non-class members.
To resolve this issue, you need to employ two overloads of the MoveTo method:
void Object::MoveTo(double speed) { MoveTo(speed, initPos); } void Object::MoveTo(double speed, Point position) { currPos = postion; }
The single-argument method calls the two-argument method, passing in the default value. This allows for a single implementation of MoveTo while maintaining the desired functionality of using a member variable as a default.
By adhering to these techniques, you can effectively utilize member variables as default arguments in C member functions without facing compilation errors.
The above is the detailed content of How to Use a Member Variable as a Default Argument in C Member Functions?. For more information, please follow other related articles on the PHP Chinese website!