显式指定方法/构造函数是否意味着不能隐式调用它?
显式指定方法/构造函数是否意味着不能隐式调用它?我的意思是,如果构造函数被指定为显式,那么它不能被某些运算符(如=)或其他方法(如转换器构造函数)隐式调用吗?
在这种情况下,将方法/构造函数指定为显式有任何重要性吗?将方法/构造函数指定为显式有什么优点?
Does specifying a method/constructor explicit mean that it can't be called implicitly? I mean if a constructor is specified as explicit, can't it be called implicitly by some operator like = or other methods like converter constructor?
In that case, does specifying a method/constructor to be explicit have any importance at all?What are the advantages of specifying a method/constructor to be explicit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在示例中,由于
MyClass
的构造函数未指定为显式,因此在调用函数doSomething()
时将其用于隐式转换。如果MyClass
的构造函数被标记为显式,那么编译器在调用doSomething()
函数时将给出错误而不是隐式转换。因此,如果您想避免此类隐式转换,那么您应该使用explicit
关键字。要添加到上面:关键字
explicit
只能用于构造函数,不能用于函数。虽然它可以用于具有多个参数的构造函数,但对于具有多个参数的构造函数,该关键字没有实际用途,因为编译器只能使用具有一个参数的构造函数进行隐式转换。In the example since constructor of
MyClass
is not specified as explicit, it is used for implicit conversion while calling the functiondoSomething()
. If constructor ofMyClass
is marked as explicit then the compiler will give an error instead of the implicit converstion while callingdoSomething()
function. So if you want to avoid such implicit conversions then you should use theexplicit
keyword.To add to the above: keyword
explicit
can be used only for constructors and not functions. Though it can be used for constructors with more than more parameters, there is no practical use of the key word for constructors with more than one parameter, since compiler can only use a constructor with one parameter for implicit conversions.函数不能具有显式说明符。 fnc 具有显式说明符是没有意义的。至于 ctor - 你的问题的答案是肯定的。声明 ctor 是显式的,这意味着隐式调用它是非法的。
什么时候有用?例如,在您的 class:
以及稍后在代码中编写:
的情况下,经常会发生这样的情况,即程序员有不同的想法,并且这种转换完全是无意的。
Function cannot have specifier explicit. It doesn't make sense for a fnc to have an explicit specifier. And as for ctor - the answer to your Q is Yes. Stating that ctor is explicit it means that it is illegal to call it implicitly.
When is it useful? In situation when for example your class:
and later in code you would write:
With line like this above very often happen that programmer has had something different in mind and this conversion is totally unintentional.