如何跳过默认参数 C++? [英] how to skip Default Arguments C++?

查看:132
本文介绍了如何跳过默认参数 C++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须用两个默认参数编写构造函数.

I have to write constructor with two default parameters.

func(int arg1 , char* arg2 = "arg2", int arg3 = 1) //example

我提供了调用构造函数并向 arg1arg2arg3 赋值的场景,预计将使用一个默认值.然后实例化另一个对象,并为 arg1arg3 赋值,并期望使用 arg2 的默认值.现在的问题是,您不能跳过"默认参数是我从文本和在线阅读的内容.它是说根据其被重载的可能性对默认参数进行排序,但该场景使用了一个默认参数,而另一个则没有.这个问题的提示告诉我重新排序参数/参数.但是,我所做的任何重新排序似乎都无法解决此问题.

I am provided the scenario where the constructor is called and a value is given to arg1 and arg2 and arg3 is expected to use a default value. Then another object is instantiated and a value is given to arg1 and arg3, and default value for arg2 is expected to be used. Now the problem is, you "can't skip" default parameters is what I'm reading from the text and online. It's saying to order the default paramters from its likliness of being overloaded, but the scenario has one default parameter used while the other isn't. The hints for this question tells me to reorder the parameters/arguments. However, no amount of reordering that I've done seem to be able to resolve this issue.

另外,不能使用重载的构造函数.这必须由一个构造函数完成.

Also, overloaded constructors can not be used. This has to be done by one constructor.

那么如何做到这一点呢?我很难过,对此有点疯狂:(

So how would one do this? I'm stumped and going a bit crazy over this :(

推荐答案

另外,不能使用重载的构造函数.这必须由一个构造函数完成.

Also, overloaded constructors can not be used. This has to be done by one constructor.

我能想到的唯一原因是可选参数具有相同的类型.在这种情况下,您被卡住了,您需要查看 命名构造函数 和/或 命名参数 习惯用法.

The only reason I can think of for this requirement is that the optional arguments have the same type. In that case, you're stuck and you'll want to look into the named constructor and/or named parameter idioms.

否则,只需定义额外的构造函数.这可能涉及一些重复的问题.默认值.

Otherwise, just define the extra constructor. This may involve some duplication wrt. the default values.

Foo(int arg1 , char const *arg2 = "arg2", int arg3 = 1)
{
    construct(arg1, arg2, arg3);
}

Foo(int arg1, int arg3)
{
    construct(arg1, "arg2", arg3);
}

这篇关于如何跳过默认参数 C++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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