为什么显式允许带有2个或更多(非默认)参数的默认构造函数和构造函数? [英] Why is explicit allowed for default constructors and constructors with 2 or more (non-default) parameters?

查看:208
本文介绍了为什么显式允许带有2个或更多(非默认)参数的默认构造函数和构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解具有一个(非默认)参数的构造函数就像隐式转换器一样,从该参数类型转换为类类型。但是, explicit 可用于限定任何构造函数,没有参数(默认构造函数)或具有2个或更多(非默认)参数的构造函数。

I understand that constructors with one (non-default) parameter act like implicit convertors, which convert from that parameter type to the class type. However, explicit can be used to qualify any constructor, those with no parameters (default constructor) or those with 2 or more (non-default) parameters.

为什么在这些构造函数上允许显式允许?有什么例子,这是有用的,以防止隐式转换某些类?

Why is explicit allowed on these constructors? Is there any example where this is useful to prevent implicit conversion of some sort?

推荐答案

一个原因当然是因为它不伤害。

One reason certainly is because it doesn't hurt.

需要它的一个原因是,如果你有第一个参数的默认参数。构造函数成为默认构造函数,但仍可用作转换构造函数

One reason where it's needed is, if you have default arguments for the first parameter. The constructor becomes a default constructor, but can still be used as converting constructor

struct A {
  explicit A(int = 0); // added it to a default constructor
};

C ++ 0x实际使用它用于多参数构造函数。在C ++ 0x中,可以使用初始化器列表来初始化类对象。如果您使用 = {...} ,则哲学是

C++0x makes actual use of it for multi parameter constructors. In C++0x, an initializer list can be used to initialize a class object. The philosophy is


  • ,然后用一种复合值来初始化对象,该复合值在概念上表示对象的抽象值,并且您希望转换为该类型。
  • if you use = { ... }, then you initialize the object with a sort of "compound value" that conceptually represents the abstract value of the object, and that you want to have converted to the type.

如果你使用 {...} 初始化器,你直接调用对象的构造函数,不一定要指定转换。

if you use a { ... } initializer, you directly call the constructors of the object, not necessarily wanting to specify a conversion.

考虑这个例子

struct String {
    // this is a non-converting constructor
    explicit A(int initialLength, int capacity);
};

struct Address {
    // converting constructor
    Address(string name, string street, string city);
};

String s = { 10, 15 }; // error!
String s1{10, 15}; // fine

Address a = { "litb", "nerdsway", "frankfurt" }; // fine

这样,C ++ 0x表示C ++ 03的决定,允许对其他构造函数显式,这不是一个坏主意。

In this way, C++0x shows that the decision of C++03, to allow explicit on other constructors, wasn't a bad idea at all.

这篇关于为什么显式允许带有2个或更多(非默认)参数的默认构造函数和构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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