Use of Explicit keyword
来源:互联网 发布:做程序员老了怎么办 编辑:程序博客网 时间:2024/06/10 15:27
In C++ it is possible to declare constructors for a class, taking a single parameter, and use those
constructors for doing type conversion. For example:
class A {
public:
A(int);
};
void f(A) {}
void g()
{
A a1 = 37;
A a2 = A(47);
A a3(57);
a1 = 67;
f(77);
}
A declaration like:
A a1 = 37;
says to call the A(int) constructor to create an A object from the integer value. Such a
constructor is called a "converting constructor".
However, this type of implicit conversion can be confusing, and there is a way of disabling it,
using a new keyword "explicit" in the constructor declaration:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = 37; // illegal
A a2 = A(47); // OK
A a3(57); // OK
a1 = 67; // illegal
f(77); // illegal
}
Using the explicit keyword, a constructor is declared to be
"nonconverting", and explicit constructor syntax is required:
class A {
public:
explicit A(int);
};
void f(A) {}
void g()
{
A a1 = A(37);
A a2 = A(47);
A a3(57);
a1 = A(67);
f(A(77));
}
Note that an expression such as:
A(47)
is closely related to function-style casts supported by C++. For example:
double d = 12.34;
int i = int(d);
Reference from : http://www.glenmccl.com/expl_cmp.htm
- Use of Explicit keyword
- 【Keyword】 explicit
- explicit keyword
- The explicit Keyword
- Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning
- Use of “this” keyword in formal parameters for static methods in C#
- 编写优质代码:C++ keyword - explicit
- Summary of keyword synchronized
- The instance of keyword
- iOS开发bug消灭之:Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit
- How to Use C's volatile Keyword
- How to Use C's volatile Keyword
- how to use the volatile keyword keil51 ?
- How to Use C's volatile Keyword
- use bbed(BBED-00200: invalid keyword (file))
- native, The Keyword Of Java
- the usage of keyword const
- keyword
- 多行合并
- 影响人生的20个小故事---绝对经典啊!(必读)
- ASP.NET实练第一练[学习.NET常用控件与XML数据的处理]
- java正则表达式; regular expression
- 开源:.NET环境下有关打印页面设置、打印机设置、打印预览对话框的实现
- Use of Explicit keyword
- COM逐步教程
- 关于在J2EE开发中的角色
- Spring 学习笔记
- 卡巴斯基安装及设置说明
- JavaScript正则表达式
- 验证有效 "日期时间" 的正则表达式(已解决闰二月)
- 一个ASP.NET调试错误
- [收藏]ORACLE函数大全