【问题标题】:How to give a variable a default value if no argument is supplied to the constructor? C++如果没有向构造函数提供参数,如何给变量一个默认值? C++
【发布时间】:2013-05-21 01:55:01
【问题描述】:

如果没有向构造函数提供任何参数,我该如何为变量赋予默认值?

例如:

class A { 

A(int x, int y)

}

int main() { 
 A(4);
}

在该示例中,我没有将值传递给 y,我将如何使 y 具有默认值 0,例如因为没有提供参数?

【问题讨论】:

    标签: c++ constructor arguments default


    【解决方案1】:

    使用默认参数,限制参数只能从右到左读取默认值,因此默认x而不默认y不是一种选择:

    A(int x, int y = 0) {}
    

    你的另一个选择是重载:

    A(int x, int y) {}
    A(int x) {/*use 0 instead of y*/}
    

    对于更复杂的组合,第二个方法特别适合委托构造函数:

    A(int x, int y) {/*do main work*/}
    A(int x) : A(x, 0) {/*this is run after the other constructor*/}
    

    不过,一旦您执行了这些操作,请注意隐式转换到您的类会更容易。您已经获得了将5 作为A 传递的可能性,而不是唯一可能的{6, 10}。在允许这些隐式转换之前仔细考虑,直到你知道你想要它们,在构造函数签名前面加上 explicit 以禁用它们。

    【讨论】:

    • @CaptainObvlious,这取决于隐式转换是否可取。不过,在大多数情况下,输入explicit 是个好主意,如果您怀疑,以后删除总是比以后添加更容易。
    • 我只是认为这将是对答案的一个很好的补充;)
    • @CaptainObvlious,我想我可以在那里添加一个花絮:p
    【解决方案2】:

    如果你想给参数传递一个默认值,你可以在构造函数声明中指定它。

    class A
    { 
        A(int x, int y = 0)
        {
        }
    };
    
    int main()
    { 
        A(4);
    }
    

    为构造函数声明默认参数时要小心。如果没有声明explicit,任何可以使用单个参数调用的构造函数都可以调用隐式转换。

    A(int x = 0, int y = 0) // <-- can invoke implicit conversion
    A(int x, int y = 0)     // <-- can invoke implicit conversion
    A(int x, int y)         // <-- does NOT implicit conversion
    

    为防止发生隐式转换,将构造函数声明为explicit

    explicit A(int x = 0, int y = 0) // <-- No longer invokes implicit conversion
    explicit A(int x, int y = 0)     // <-- No longer invokes conversion
    A(int x, int y)                  // <-- does not require explicit keyword
    

    【讨论】:

      【解决方案3】:

      你必须给默认变量所以构造函数变成

      A(int x=5, int y=4)
      
      }
      

      y 的默认值为 4,x 的默认值为 5

      【讨论】:

        猜你喜欢
        • 2014-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        • 2011-03-24
        相关资源
        最近更新 更多