在C ++中以较少的参数调用构造函数 [英] Constructor being called with less arguments in C++

查看:107
本文介绍了在C ++中以较少的参数调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Foo类,并具有以下构造函数:

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?

那我该如何赋予默认值?

推荐答案

除非签名末尾的参数具有默认值,否则不要这样,例如:

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);

这篇关于在C ++中以较少的参数调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆