explicit关键字

一:

  explicit在QT的开发中,是经常见到的关键字,现在来讲讲下这个关键字的作用。

  首先,类的构造函数一般是隐式自动转换的,代码如下:

  class TestMy
  {
  public:
    TestMy()
    {
      cout<<"默认构造函数1"<<endl;
    }
    TestMy(const char *str)
    {
      cout<<"默认构造函数2"<<endl;
    }
    TestMy(int size)
    {
      mSize=size;
      cout<<"默认构造函数3"<<endl;
    }
    char *name;
    int mSize;
  };
  void test01()
  {

    TestMy  str4;      //调用无参数的构造函数,因为TestMy提供了两个带参数的构造函数,这个不提供的话,这样写编译会报错
    TestMy str1="abc";       //调用的是TestMy(const  char  *str)
    TestMy str2(20);           //调用的是TestMy(int  size)
    TestMy  str3=40;          //调用的是TestMy(int  size)

    TestMy  str5='A';         //调用的是TestMy(int  size),且size等于'A'对应的ASCCI值
  }
  int main()
  {
    test01();
    return 0;
  }

  运行的结果如下: 

  默认构造函数1
  默认构造函数2
  默认构造函数3
  默认构造函数3

  默认构造函数3

  //================================================

  解析:上面的代码中, "TestMy str3=40" 这句为什么是可以的呢? 在C++中, 如果构造函数只有一个参数时, 那么在编译的时候就会有一个缺省的转换操作:将该构造函数对应数据类型的数据转换为该类对象. 也就是说 "TestMy str3=40" 这段代码, 编译器自动将整型转换为TestMy类对象, 实际上等同于下面的操作:

  TestMy str3(40);
  或
  TestMy temp(40);
  TestMy str3 = temp;

  但是上面的代码容易给人易解,是会str3开辟个40个char类型大小的空间,还是说将赋值字符串为“40”,所以上面为了解决这种误解,就得加上explicit这个关键字。

二:

  explicit关键字的作用就是防止类构造函数的隐式自动转换,通常只对有一个参数的类构造函数有效。

  上面的代码更改如下:

  class TestMy
  {
  public:
    TestMy()
    {
      cout<<"默认构造函数1"<<endl;
    }
    TestMy(const char *str)
    {
      cout<<"默认构造函数2"<<endl;
    }
    explicit  TestMy(int size)
    {
      mSize=size;
      cout<<"默认构造函数3"<<endl;
    }
    char *name;
    int mSize;
  };
  void test01()
  {

    TestMy  str4;      //调用无参数的构造函数,因为TestMy提供了两个带参数的构造函数,这个不提供的话,这样写编译会报错
    TestMy str1="abc";       //调用的是TestMy(const  char  *str)
    TestMy str2(20);           //调用的是TestMy(int  size)\

    TestMy  str3=40;            

  }
  int main()
  {
    test01();
    return 0;
  }

  注:编译的时候TestMy  str3=40;       这里就会报错,因为取消了隐式的转换。

posted @ 2021-02-08 15:13  田大叔  阅读(261)  评论(0)    收藏  举报