开发者

Issue with Default Arguments

开发者 https://www.devze.com 2023-02-19 20:58 出处:网络
In the Book C++ Primer by Stanley B. Lippman*,* Josée Lajoie in Chapter 14.2 of Class Constructors it states:

In the Book C++ Primer by Stanley B. Lippman*,* Josée Lajoie

in Chapter 14.2 of Class Constructors it states:

Should we also provide support for specifying an opening balance but no client name? As it happens, the class specification disallows this explicitly. Our two-parameter constructor with a default second argument provides a complete interface for accepting initial values for the data members of class Account that can be set by the user:

class Account {
public:
       // default constructor ...
       Account();

       // parameter names are not necessary in declaration
       Account( const char*, double=0.0 ); 

       const char* name() { return _name; } // What is this for??
       // ...
private:
       // ...
};

The following are both legal Account class object definitions passing one or two arguments to our constructor:

int main()
{
        // ok: both invoke two-parameter constructor
        Account acct( "Ethan Stern" ); 

How does this Invoke the 2-parameter constructor whe开发者_运维技巧n it has not been declared with single argument??

        Account *pact = new Account( "Michael Lieberman", 5000 );

And how does the above line call the constructor with default arguments

        if ( strcmp( acct.name(), pact->name() ))
             // ...
}

The book seems to be highly unclear with incomplete codes. Need a good explanation on Constructors. Please clarify.


This isn't about constuctors, this is about default arguments.

void f(int x, int y = 5)
{
   //blah
}

when you call it providing less arguments, it uses the values of default arguments. E.g.

f(3); //equivalent to f(3, 5);

If one of the function parameters has a default value, then all successive parameters must have ones too.

void f(int x, int y = 3, int z = 4)
{
    //blah
}

f(0);    // f(0, 3, 4)
f(1, 2); //f(1, 2, 4)
f(10, 30, 20); //explicitly specifying arguments

HTH

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号