您的位置:首页 > 编程语言 > C语言/C++

C++中的explicit关键字(转)

2017-08-30 11:12 316 查看
原创作品,转载请标明http://blog.csdn.NET/xiejingfa/article/details/48369081

问题

我们知道,C++在内置类型之间存在隐式类型转换。而在类类型中,也存在这样一种类型转换:当一个类的构造函数只有参数时,会将该类型的一个值隐式转换为对应的类类型。比如下面一个例子:

[cpp] view plain copy print?#include <iostream>
using namespace std;

class Example
{
public:
int e;
Example(int n)
{
e = n;
}
};

int main()
{
Example example1(100); // 调用了默认构造函数
Example example2 = 200; // 进行了隐式初始化
cout << example1.e << endl; // 输出100
cout << example2.e << endl; // 输出200
}
#include <iostream>

using namespace std;


class Example

{

public:

int e;

Example(int n)

{

e = n;

}

};

int main()

{

Example example1(100); // 调用了默认构造函数

Example example2 = 200; // 进行了隐式初始化

cout << example1.e << endl; // 输出100

cout << example2.e << endl; // 输出200

}隐式类型转换往往容易发生错误,为了禁止上述的隐式类型转换可以使用explicit关键字。

explicit关键字

explicit关键字用来修饰类的构造函数,被该关键字修饰的类,不能发生上述的隐式类型转换,只能以显形的方式进行类型转换。

[cpp] view plain copy print?#include <iostream>
using namespace std;

class Example
{
public:
int e;
explicit Example(int n)
{
e = n;
}
};

int main()
{

Example example1 = 100; // Error 不存在从”int”到”Example”的适当构造函数
Example example2 = static_cast<Example>(200); // 显示转换
cout << example2.e; // 输出200
}
#include <iostream>

using namespace std;


class Example

{

public:

int e;

explicit Example(int n)

{

e = n;

}

};

int main()

{

Example example1 = 100; // Error 不存在从"int"到"Example"的适当构造函数
Example example2 = static_cast<Example>(200); // 显示转换
cout << example2.e;    // 输出200


}

总结

1、explicit关键可以屏蔽编译器缺省的隐式类型转换;

2、explicit关键字只能用于类内部的构造函数声明,而不能于在类外部的函数声明;

3、explicit只有在构造器只传一个参数的情况下有意义,当构造函数的参数超过两个时会自动取消隐式类型转换。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++