【问题标题】:Creating constructor with default value or with setValue使用默认值或 setValue 创建构造函数
【发布时间】:2016-02-13 11:07:00
【问题描述】:

我想知道是否有可能在 C++ 中创建一个使用例如 float 的构造函数,但这个 float 不是必需的。我的意思是:

构造函数:

Fruit::Fruit(float weight)
{
    weight = 1;
    this->setWeight(weight);
}

我需要使用一个构造函数来做类似的事情:

Fruit pear = Fruit(5);          - gives a pear with weight 5
Fruit strawberry = Fruit();     - gives a strawberry with default weight 1

【问题讨论】:

    标签: c++ constructor default-value


    【解决方案1】:

    使用类内初始化,可以显着清理代码:

    class Fruit {
    public:
    
      Fruit() = default;
      Fruit(float weight) : weight_{weight} {}
    
      // ... other members
    
    private:
      float weight_ { 1.0f };
    
    };
    

    这样,如果调用默认 c'tor,则会自动创建默认权重“1”。这具有显着清理构造函数中的初始化列表的好处。考虑一下如果您有许多默认初始化为垃圾值(即任何内置类型)的类成员会发生什么。然后你必须在 c'tor 初始化器列表中显式地初始化它们,这很麻烦。通过类内初始化,您可以在成员声明站点执行此操作。

    【讨论】:

      【解决方案2】:

      是的,这可以通过在参数列表中使用= 指定值来完成:

      Fruit::Fruit(float weight = 1)
      {
          this->setWeight(weight);
      }
      
      猜你喜欢
      • 1970-01-01
      • 2018-10-02
      • 2012-11-03
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      相关资源
      最近更新 更多