Two constructors, which is default?

后端 未结 6 1513
深忆病人
深忆病人 2020-12-12 02:29

Okay I got a pretty simple assignment.

I got these two constructors for class Person:

Person( const string &, const string &, const string &a         


        
相关标签:
6条回答
  • 2020-12-12 02:38

    A default constructor is a constructor that either has no arguments or it has some but all of them provide default values. In your case, if both of your constructors have all of their arguments with default values, then a call like

    Person p;
    

    will be ambiguous. Think about it: which one is to be called?

    0 讨论(0)
  • 2020-12-12 02:49

    A default constructor is a constructor that either has no arguments, or if it has arguments, all the arguments have default values. So neither one of these could qualify as default constructor.

    0 讨论(0)
  • 2020-12-12 02:54

    According to the C++ Standard

    4 A default constructor for a class X is a constructor of class X that can be called without an argument.

    From your post it is not clear what default values you are speaking about. Neither of your declarations is the default constructor.

    If you are speaking about default arguments as in the declaration

    Person( const string & = "", const string & = "", const string & = "",
    const string & = "" );
    

    Then this declaration is a declaration of the default constructor because it can be called without any explicitly specified argument.

    It is interesting to note that the same constructor can be a default constructor and a non-default constructor at the same time. At least the C++ Standard does not say anything that forbids this.

    For example

    struct A
    {
       A( int x );
       int x;
    };
    
    A a1; // error: there is no default constructor
    
    A::A( int x = 0 ) : x( x ) {}
    
    A a2; // well-formed there is a default constructor.
    
    0 讨论(0)
  • 2020-12-12 02:56

    If you ask which could be called; that depends on how you create object.

    For example;

    1 - First is called

    Person person = new Person("a","b","c");
    

    2 - Second is called

    Person person = new Person("a","b","c","d");
    
    0 讨论(0)
  • 2020-12-12 03:01

    Neither of these two constructors is the default one.

    A default constructor is one that you could invoke with no parameters - either because

    • the constructor has no arguments, or
    • all of its parameters have default values.

    Both constructors in your example require that parameters be passed to them, so neither of them is a default one.

    0 讨论(0)
  • 2020-12-12 03:03

    Both the constructors will be matched only when the signature of the call statement matches. The default constructor is always the constructor with no arguments

    Person(){}
    
    0 讨论(0)
提交回复
热议问题