C++中的explicit关键字(转)
来源:互联网 发布:口袋妖怪编辑队伍软件 编辑:程序博客网 时间:2024/06/11 03:53
原创作品,转载请标明:http://blog.csdn.NET/xiejingfa/article/details/48369081
问题
我们知道,C++在内置类型之间存在隐式类型转换。而在类类型中,也存在这样一种类型转换:当一个类的构造函数只有参数时,会将该类型的一个值隐式转换为对应的类类型。比如下面一个例子:
- #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关键字用来修饰类的构造函数,被该关键字修饰的类,不能发生上述的隐式类型转换,只能以显形的方式进行类型转换。
- #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++中的explicit关键字(转)
- c++中的explicit关键字【转】
- [转]C++中的explicit关键字
- extern “C”总结 C++中的explicit关键字
- 转 - C++中的explicit关键字
- c++中的explicit关键字
- c++中的explicit关键字
- c++中的explicit关键字
- c++中的explicit关键字
- c++中的explicit关键字
- C++中的 explicit 关键字
- c++中的explicit关键字
- C++中的explicit关键字
- C++中的explicit关键字
- c++中的explicit关键字
- c++中的explicit关键字
- C++中的explicit关键字
- c++中的explicit关键字
- CSS怎么调用系统没有的字体
- apk反编译
- SQL Tuning 基础概述04
- SpringMVC中使用StandardServletMultipartResolver上传文件实例
- 继承中的super限定
- C++中的explicit关键字(转)
- 冒泡排序c++
- ios根据文件路径,将文件进行MD5加密
- 质数(素数)
- php socket编程
- android 关于apk 打包后的地图定位和导航失败的问题
- 第二十五篇:JAVA拖拽选择文件
- C++ 函数重载
- Shipyard的几个概念