Home > Backend Development > C++ > body text

How to Use a Member Variable as a Default Argument in C Member Functions?

Susan Sarandon
Release: 2024-11-14 18:11:02
Original
768 people have browsed it

How to Use a Member Variable as a Default Argument in C   Member Functions?

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template