从另一个参数的值设置默认参数值

Lau*_*kas 1 c++ parameters

是否有可能实现这样的功能,如果没有指定,参数的值将默认为另一个参数的值?

例:

class Health
{
public:
    // If current is not specified, its value defaults to max's value
    Health(int max, int current = max) : max_(max), current_(current) { }
    int max_;
    int current_;
};
Run Code Online (Sandbox Code Playgroud)

就像现在一样,我收到编译错误:

error: 'max' was not declared in this scope
Health(int max, int current = max) : max_(max), current_(current) { }
                              ^
Run Code Online (Sandbox Code Playgroud)

Jar*_*d42 8

你必须提供过载:

class Health
{
public:
    Health(int max, int current) : max_(max), current_(current) { }

    Health(int max) : max_(max), current_(max) {}
    // or `Health(int max) : Health(max, max) {}` since C++11

    int max_;
    int current_;
};
Run Code Online (Sandbox Code Playgroud)