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

时间:2015-08-12 14:36:23

标签: 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_;
};

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

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

2 个答案:

答案 0 :(得分: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_;
};

答案 1 :(得分:0)

您可以将参数默认为不应接受的值,然后在初始化中使用?运算符进行检查

class Health
{
public:
    // If current is not specified, its value defaults to max's value
    Health(int max, int current = 0) : max_(max), current_(current == 0 ? max : current) { }
    int max_;
    int current_;
};