2009年3月20日 星期五

The explicit Keyword in 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, 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);
And the following is illegal since the constructor is explicit

A a7 = 7;

沒有留言:

張貼留言