zoukankan      html  css  js  c++  java
  • C++ 中的explicit关键字

    explicit关键字在c++中是为了防止隐式转换

    (1)

    explicit

    此关键字只能对用户自己定义的对象起作用,不对默认构造函数起作用
    此关键字只能够修饰构造函数。而且构造函数的参数只能有一个。。

    (2)何时用explicit

    当我们不希望自动类型转换的时候用,其实标准库好多构造函数都是explicit的

    比如说vector <int> ivec(10);  //这种定义看起来一目了然

    不能写成vector <int> ivec=10;//此种定义让程序员感到疑惑

    (3)何时不用explicit

    当我们需要隐式转换的时候

    比如说String类的一个构造函数

    String(const char*);

    定义成这样的好处,在需要隐式转化的时候编译器会自动地帮我们转换,标准库里面的String就是一个好的证明。

    具体来说:

    我们可以这样String str="helloworld";//直接调用构造函数

    String str="hello"+str+"world";

    调用重载的+操作符号,此过程相当于:
    String temp("hello"); //调用构造函数

    String str=temp+str;

    String t("world");//调用构造函数

    String str=str+t;

    明白隐式转换在我们自己写类的时候,尤其是些操纵内存的类的时候很有用。

  • 相关阅读:
    hdu 1429 胜利大逃亡(续)(BFS+位压缩)
    hdu 2955 Robberies
    POJ—Building a Space Station
    POJ-1287 Networking
    POJ-1251 Jungle Roads
    BFS ZOJ problem-1671 Waking Ant
    POJ-1308 Is It A Tree?
    poj 1611The Suspects
    POJ Wireless Network
    POJ 2524 Ubiquitous Religions
  • 原文地址:https://www.cnblogs.com/zhaodun/p/7146578.html
Copyright © 2011-2022 走看看