c++ - "explicit"关键字对默认构造函数有影响吗?

标签 c++ default-constructor explicit

是否有理由为不带任何参数的构造函数使用 explicit 关键字?它有什么作用吗?我想知道,因为我刚刚遇到了这条线

explicit char_separator()

在记录 boost::char_separator 的页面末尾附近,但这里没有进一步解释。

最佳答案

阅读 explanation of members :

explicit char_separator(const Char* dropped_delims,
                        const Char* kept_delims = "",
                        empty_token_policy empty_tokens = drop_empty_tokens)
explicit char_separator()

第一个构造函数的 explicit 关键字需要显式创建 char_separator 类型的对象。 What does the explicit keyword mean in C++?很好地涵盖了显式关键字。

第二个构造函数的 explicit 关键字是噪音,被忽略。

编辑

来自 c++ 标准:

7.1.2 p6 告诉:

The explicit specifier shall be used only in declarations of constructors within a class declaration; see 12.3.1.

12.3.1 p2 告诉:

An explicit constructor constructs objects just like non-explicit constructors, but does so only where direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used. A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value-initialization (8.5). [Example:

class Z {
public:
explicit Z();
explicit Z(int);
// ...
};
Z a;               // OK: default-initialization performed
Z a1 = 1;          // error: no implicit conversion
Z a3 = Z(1);       // OK: direct initialization syntax used
Z a2(1);           // OK: direct initialization syntax used
Z* p = new Z(1);   // OK: direct initialization syntax used
Z a4 = (Z)1;       // OK: explicit cast used
Z a5 = static_cast<Z>(1); // OK: explicit cast used

—end example]

因此,带有 explicit 关键字的默认构造函数与没有 this 关键字的默认构造函数相同。

关于c++ - "explicit"关键字对默认构造函数有影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6775336/

相关文章:

c++ - OpenCV contourArea() 不工作

c++ - 顺序/在线 kmeans 聚类,它是如何工作的?现有代码?

c++ - 使用来自 Cython 构造函数的参数初始化 C++ 对象

使用 fstream fin 从文件读取时 C++ 程序崩溃

c++ - 执行了多个功能但未正确运行

c++ - 是否存在删除了 ctor 的类有用的情况?

kotlin - Kotlin默认构造函数

wpf - Binding UpdateSourceTrigger=Explicit,在程序启动时更新源

c++ - 为什么编译器选择 bool 而不是 string 来进行 L""的隐式类型转换?

c++ - 在函数中传递显式字符数组?