2012年2月15日 星期三

Explicit Constructors


The keyword explicit is used to specify that a constructor may only be used for object instantiation and not for automatic conversion. explicit should only be applied to single-argument constructors, or contructors that can be invoked with one argument, since the idea is to avoid automatic conversion of one type to another (class) type.

Here's an example that demonstrates the effect.

Example 4-17 – Explicit constructors

1      // File: ex4-17.cpp - explicit constructors
2     
3      #include <iostream>
4      using namespace std;
5     
6      class A
7      {
8      public:
9          A(int);                // non-explicit ctor
10      };
11     
12     
13      class B
14      {
15      public:
16          explicit B(int);            // explicit ctor
17      };
18     
19      A::A(int) {
20          cout << "A ctor called\n";
21      }
22     
23      B::B(int) {                 // do not repeat keyword explicit
24          cout << "B ctor called\n";
25      }
26     
27      void funkA(A object) {
28          cout << "funkA called\n";
29      }
30     
31      void funkB(B object) {
32          cout << "funkB called\n";
33      }
34     
35      void funkAB(A obj)
36      {
37          cout << "funkAB(A) called\n";
38      }
39     
40      void funkAB(B obj)
41      {
42          cout << "funkAB(B) called\n";
43      }
44      int main()
45      {
46          A objA(2);        // instantiate an A object
47          B objB(3);        // instantiate a B object
48     
49          funkA(objA);    // call funkA() with an exact argument match
50     
51          funkA(9);        // call funkA() with an non-exact argument match
52     
53          funkB(objB);    // call funkB() with an exact argument match
54     
55      //  funkB(16);  // compile error: cannot convert int to a B object
56     
57          funkAB(6);        // compile error if B(int) is not explicit
58     
59          return 0;
60      }


******  Output  ******

A ctor called
B ctor called
funkA called
A ctor called
funkA called
funkB called
funkAB(A) called

沒有留言:

張貼留言