about "explicit", one of the C++ keywords

explicit修饰的构造函数不能担任转换函数
in ANSI/ISO C++ Professional Programmer's Handbook it said,

explicit Constructors
A constructor that takes a single argument is, by default, an implicit
conversion operator, which converts its argument to an object of its class .
for example, declear such a class
class CArray
{
public:
CArray(void);
explicit CArray(int size);
......
};
the explicit is very important for this declearation. without the keyword the compiler may convert int to CArray like follows
CArray arr;
......
arr = 8;
the c++ compiler will convert 8 to an instance of class CArray with 8 elements and assign the instance to arr. actually it's wrong (though with no compile or link errors). but we'll get some compile error while using explicit in declearation and avoid it. :)

notes: explicit同样也能阻止"以赋值语法进行带有转型操作的初始化".

0 comments: