Home >Backend Development >C++ >Can I Use Member Variables as Default Arguments in C Methods?
When creating a class with methods that take multiple arguments, it can be beneficial to make some arguments optional. By using the default argument feature, you can set a default value for an argument that can be used when no value is provided by the client code.
In your case, you attempted to use a member variable (initPos) as the default argument for your MoveTo member function. However, the compiler issued an error indicating an invalid use of a non-static data member.
Member variables are not accessible in the method's scope by default, as they are considered part of the object's state and not the method's context. As a result, by default arguments in member functions can only depend on in-class or global scope elements.
To resolve this issue, you need to resort to method overloading. Method overloading allows you to create multiple versions of the same method with different signatures. Here's how to implement it in your code:
// Object.h class Object { public: ... void MoveTo(double speed); void MoveTo(double speed, Point position); protected: Point initPos; Point currPos; };
// Object.c void Object::MoveTo(double speed) { MoveTo(speed, initPos); } void Object::MoveTo(double speed, Point position) { // Everything is done here. }
By defining two versions of the MoveTo method, you can effectively provide a default argument without relying on the member variable directly. The MoveTo(double) method calls the MoveTo(double, Point) method with the initPos value as the second argument, allowing you to preserve the desired functionality and avoid compiler errors.
The above is the detailed content of Can I Use Member Variables as Default Arguments in C Methods?. For more information, please follow other related articles on the PHP Chinese website!