其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
Use of Explicit keyword

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站


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




相关文章

相关软件