Constructor being called with less arguments in C++

半城伤御伤魂 提交于 2020-01-02 19:52:49

问题


I have class Foo with a constructor as given:

class Foo {
 public:
   Foo(int w, char x, int y, int z);
   ...
 };

int main()
{
   Foo abc (10, 'a');
}

Can I use that constructor like this? When constructor signature do not match?

So How do I give default value?


回答1:


Not unless the parameters at the tail of the signature have defaults, for example:

class Foo {
public:
    Foo(int w, char x, int y=5, int z=0);
    ...
};

If there are defaults, then you can supply only the non-defaulted parameters, and optionally some defaulted ones, i.e. any of the following invocations would be valid:

Foo abc (10, 'a');
Foo abc (10, 'a', 3);
Foo abc (10, 'a', 42, 11);



回答2:


You cannot, unless the missing constructor arguments have default values.

For example, you can do this:

class Foo {
 public:
   Foo(int w, char x, int y = 0, int z = 1);
   ...
 };

int main()
{
   Foo abc (10, 'a'); /* y is implicitly 0 and z is 1 */
}



回答3:


To provide default parameters, equal them to zero or else with some default value.

class Foo {
 public:
   Foo(int w, char x, int y = 0, int z = 0) { }
   // ...
 };

Or,

class Foo {
 public:
   Foo(int w, char x, int = 0, int = 0);
   // ...
 };

// Define your constructor here, note 'no default parameters'
Foo::Foo(int w, char x, int y, int z) { }



回答4:


No - if there is no constructor which accepts two arguments with matching types, you can't.




回答5:


I'd suggest to overload the constructor rather than providing default values.

class Foo {
public:
    Foo(int w, char x); // y = 0, z = 1
    Foo(int w, char x, int y); // z = 1
    Foo(int w, char x, int y, int z);
};

It's a matter of style in the end: cons you need to duplicate the initializer list, because constructors cannot be chained, pros readability IMHO. Make sure to read this thread.



来源:https://stackoverflow.com/questions/8576481/constructor-being-called-with-less-arguments-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!