explicit & implicit constructors

This question already has an answer here:

  • What does the explicit keyword mean? 11 answers

  • Take this as an example:

    class complexNumbers {
          double real, img;
        public:
          complexNumbers() : real(0), img(0) { }
          complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; }
          complexNumbers( double r, double i = 0.0) { real = r; img = i; }
          friend void display(complexNumbers cx);
        };
        void display(complexNumbers cx){
          cout<<&quot;Real Part: &quot;<<cx.real<<&quot; Imag Part: &quot;<<cx.img<<endl;
        }
        int main() {
          complexNumbers one(1);
          display(one);
          display(300);   //This code compiles just fine and produces the ouput Real Part: 300 Imag Part: 0
          return 0;
        }
    

    Since the method display expects an object/instance of the class complexNumbers as the argument, when we pass a decimal value of 300, an implicit conversion happens in-place.

    To overcome this situation, we have to force the compiler to create an object using explicit construction only, as given below:

     explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; }  //By Using explicit keyword, we force the compiler to not to do any implicit conversion.
    

    and after this constructor is present in your class, the statement display(300); will give an error.

    链接地址: http://www.djcxy.com/p/24564.html

    上一篇: C ++ Functors

    下一篇: 显式和隐式构造函数