分享

C++中 explicit 关键字作用详解

 My镜像站 2011-11-16

【前言】

    今天遇到了个问题,被人问及 explicit 作用的时候,想不起来了C++ 中 explicit 关键字作用详解 - 曹操(小鱼儿) - 系统分析师 曹操。因此重新温习了一下,详细描述如下:

【正文】

    简单的说,就是类的构造函数禁止隐式类型转换。先看一看微软大哥是如何说的:

This keyword is a declaration specifier that can only be applied to inclass constructor declarations. Constructors declared explicit will not be considered for implicit conversions. For example:

class X {  public:     explicit X(int);      //legal     explicit X(double) {   //legal        // ...     }  };    explicit X::X(int) {}      //illegal

An explicit constructor cannot take part in implicit conversions. It can only be used to explicitly construct an object. For example, with the class declared above:

void f(X) {}  void g(int I) {     f(i);      // will cause error  }  void h() {     X x1(1);      // legal  }

The function call f(i) fails because there is no available implicit conversion from int to X.

Note   It is meaningless to apply explicit to constructors with multiple arguments, since such constructors cannot take part in implicit conversions.

总结一下,大致意思就是:

(1) explicit 只能在类的内部使用,不能在外面声明。

(2)声明了explicit以后,就不允许隐式转换了。

(3)explicit对于多个参数的构造函数无任何意义。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多