The explicit Keyword
C++A constructor declared with only one argument and without the explicit keyword is a converting constructor. You can construct objects with a converting constructor using the assignment operator. Declaring a constructor of this type with the explicit keyword prevents this behavior. The explicit keyword controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are converting constructors.
class A
{ public:
A();
A(int);
A(const char*, int = 0);
};
The following declarations are legal.
A c = 1;
A d = "Venditti";
The first declaration is equivalent to A c = A(1).
If you declare the constructor of the class with the explicit keyword, the previous declarations would be illegal.
For example, if you declare the class as:
class A
{ public:
explicit A();
explicit A(int);
explicit A(const char*, int = 0);
};
You can only assign values that match the values of the class type.
For example, the following statements will be legal:
A a1;
A a2 = A(1);
A a3(1);
A a4 = A("Venditti");
A* p = new A(1);
A a5 = (A)1;
A a6 = static_cast<a>(1);
Ref:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc06explicit_keyword.htm
没有评论:
发表评论