explicit关键字作用的讨论

作用:禁止单参数构造函数被用于自动转型转换的执行。

View Code
 1 #include <iostream> 
2 using namespace std;
3
4 class Sample
5 {
6 public:
7 Sample(int i) : x(i) {}
8 private:
9 int x;
10
11 };
12 void main()
13 {
14 Sample s = 1;
15 }

s = 1;会调用Sample的构造函数,构造s对象。

:构造函数中,只能有一个未赋默认值的形参。

如果需要禁用这种操作执行,就需要在构造函数前加explicit关键字。

原文地址:https://www.cnblogs.com/xuxu8511/p/2436039.html