Translations of this page?:

explicit

如果构造函数被声明为explicit, 在使用这个构造函数时就不会进行自动的类型转换 -- 但传递给构造函数的参数仍可能会被转换. 例如:

    struct foo {
      explicit foo( int a )
        : a_( a )
      { }
 
      int a_;
    };
 
    int bar( const foo & f ) {
      return f.a_;
    }
 
    bar( 1 );  // 失败, 因为explicit禁止int到foo的隐式(implicit)类型转换.
 
 
    bar( foo( 1 ) );  // 正确 -- 显式调用explicit构造函数.
 
    bar( static_cast<foo>( 1 ) );  // 正确 -- 通过explicit cast调用 explicit构造函数.
 
    bar( foo( 1.0 ) );  // 正确 -- 显式调用explicit构造函数, 参数自动从浮点转换成整型.
 
• • • SitemapRecent changesRSScc