简体   繁体   English

为什么默认参数构造函数被称为默认构造函数

[英]Why default argument constructor is called as default constructor

Class A {
public:
       A(int i = 0, int k = 0) {} // default constructor WHY ??
       ~A() {}
};
int main()
{
  A a; // This creates object using defined default 
       // constructor but the constructor still has two arguments
  A b(1,2); // Called as parametrized one
}

Why this default argument constructor is default constructor.为什么这个默认参数构造函数是默认构造函数。 Why it is not called Parametrized constructor or default parametrized constructor because even if this constructor is called with no arguments it does contain two arguments ??为什么它不被称为参数化构造函数或默认参数化构造函数,因为即使在没有参数的情况下调用此构造函数,它也确实包含两个参数?? Is there any specific reason or its just because the standard says so.是否有任何特定原因或仅仅是因为标准如此说明。

C++11 §12.1 Constructors C++11 §12.1 构造函数

A default constructor for a class X is a constructor of class X that can be called without an argument.类 X 的默认构造函数是类 X 的构造函数,无需参数即可调用。

This is the definition of default constructor.这是默认构造函数的定义。 A constructor that supplies default arguments for all its parameters can be called without argument, thus fits the definition.为其所有参数提供默认参数的构造函数可以在没有参数的情况下调用,因此符合定义。

By definition, a default constructor is one that can be called without arguments.根据定义,默认构造函数是可以不带参数调用的构造函数。 Yours cleary fits that definition, since both parameters have default value.您的显然符合该定义,因为这两个参数都有默认值。

The asnwer to "why" is, I'd say, simply because C++ standard says so. “为什么”的答案是,我想说,仅仅是因为 C++ 标准是这样说的。 The choice of constructor to be called is done by overload resolution based on number and types of parameters, just like with other functions.要调用的构造函数的选择是通过基于参数数量和类型的重载决议完成的,就像其他函数一样。

The feature of constructor overload allow the compiler to infer which constructor to call based on the passed arguments.构造函数重载的特性允许编译器根据传递的参数推断调用哪个构造函数。 The default constructor is just the constructor which is resolved for no arguments, as in默认构造函数只是没有参数解析的构造函数,如

A a;

or或者

A a=A();

And again due to parameters overloading only a single constructor can be resolved for each set.再次由于参数重载,每个集合只能解析一个构造函数。 So, if all parameters have default values => it is ok to call 'A()' => it is the default constructor.因此,如果所有参数都有默认值 => 可以调用 'A()' => 它是默认构造函数。

根据 c++ 标准,默认构造函数是可以不带参数调用的构造函数。这也是您提出问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM