【问题标题】:Set default parameter value from another paramater's value [duplicate]从另一个参数的值设置默认参数值[重复]
【发布时间】:2015-11-05 05:52:54
【问题描述】:

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

例子:

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) { }
                              ^

【问题讨论】:

    标签: c++ parameters


    【解决方案1】:

    你必须提供重载:

    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_;
    };
    

    【讨论】:

      【解决方案2】:

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

      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_;
      };
      

      【讨论】:

      • 如果 0 是当前的有效值怎么办?
      • 或使用const int* current=nullptr(或optional<int>),但似乎过于复杂。
      • @Jarod42 指针对于调用者来说非常丑陋(“你的意思是我不能传递文字是什么意思?!”),但optional 是公平的游戏,我会说。
      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 2018-01-22
      • 2017-02-03
      • 2019-08-25
      • 1970-01-01
      • 2015-02-19
      • 2018-11-27
      • 1970-01-01
      相关资源
      最近更新 更多