显式和隐式构造函数

explicit & implicit constructors

本文关键字:构造函数      更新时间:2023-10-16

我已经在stackoverflow上阅读了许多关于隐式和显式构造函数的问题,但是我仍然无法区分隐式和显式构造函数。

我想知道是否有人可以给我一个很好的定义和一些例子,或者可能指导我去解释这个概念的书/资源

以以下为例:

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;
    }

由于方法display需要类complexNumbers的对象/实例作为参数,因此当我们传递一个十进制值300时,将在适当的位置进行隐式转换。

为了克服这种情况,我们必须强制编译器只使用显式构造创建对象,如下所示:

 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.

并且在这个constructor出现在您的类之后,语句display(300);将给出一个错误