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

    今天在《C++ Standard Library》中看到 explicit 的作用,在这里做一下笔记,以备下次再次忘记该关键字的作用。

      By using the keyword explicit, you can prohibit a single argument constructor from defining an automatic type conversion. A typical example of the need for this feature is in a collection class in which you can pass the initial size as constructor argument. For example, you could declare a constructor that has an argument for the initial size of a stack:

      通过使用关键字 explicit,你可以禁止一个参数的构造函数定义一个自动类型转换。对于这个需要的一个典型的例子是下面这样的一个集合类:

    					
       class Stack {
           explicit Stack(int size);      // create stack with initial size
           ...
       };
    

      Here, the use of explicit is rather important. Without explicit this constructor would define an automatic type conversion from int to Stack. If this happens, you could assign an int to a Stack:

    					
       Stack s;
       ...
       s = 40;      // Oops, creates a new Stack for 40 elements and assigns it to s
    

      The automatic type conversion would convert the 40 to a stack with 40 elements and then assign it to s. This is probably not what was intended. By declaring the int constructor as explicit, such an assignment results in an error at compile time.

    Note that explicit also rules out the initialization with type conversion by using the assignment syntax:

    					
       Stack s1(40);        // OK
       Stack s2 = 40;       // ERROR
    
  • 相关阅读:
    链接脚本语法
    STM32 硬件IIC接口总线
    C99一些特性
    oneid与用户标签之间的相互打通 实现用户标签
    图计算实现ID_Mapping、Oneid打通数据孤岛
    对于hive使用的一点记录
    centos7 hue安装
    Kafka监控安装
    hadoop2.6.0集群搭建
    centos6+cdh5.4.0 离线搭建cdh搭建
  • 原文地址:https://www.cnblogs.com/wiessharling/p/3975743.html
Copyright © 2011-2022 走看看