开发者

Is there a way to have dynamic default arguments?

开发者 https://www.devze.com 2023-04-12 04:05 出处:网络
I\'m trying to make a class where the user can modify member variables to change the default arguments of its member functions.

I'm trying to make a class where the user can modify member variables to change the default arguments of its member functions.

class Class
{
    public int Member;

    public void Method(int Argument = Member)
    {
        // This compiles fine, until I try to actually use
        // the method elsewhere in code!

        // "Error: need 'this' to access member Member"
    }
}

My workaround so far has been to use magic numbers, which obviously isn't ideal.

public void Method(int Argument = 123)
{
    int RealArgument;

    if (Argu开发者_开发问答ment == 123) RealArgument = Member;
    else RealArgument = Argument;
}

Is there a better way, or am I stuck with this "hack" solution?


Yep, forget about the default argument.

class Class
{
    public int Member;

    public void Method(int Argument)
    {
        ...
    }

    public void Method()
    {
        Method(Member);
    }
}

No need for trickery here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号