C++编程失乐园

致力于解决论坛的不足,探讨C++的原理

C++随笔 之 explicit 关键字(转载)

explicit关键字用于取消构造函数的隐式转换,对有多个参数的构造函数使用explicit是个语法错误。


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);

posted on 2007-01-16 13:21 木木头 阅读(407) 评论(0)  编辑 收藏 引用 所属分类: C++特性


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2007年1月>
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910

统计

常用链接

留言簿(3)

随笔分类(29)

搜索

最新随笔

最新评论