explicit specifier
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
指定构造函数和(C++11 起)转换运算符,不允许隐式转换
原文:
Specifies constructors and (C++11 起) conversion operators that don't allow implicit conversions
[编辑] 语法
explicit class_name ( params ) | |||||||||
explicit operator type ( ) (C++11 起) | |||||||||
[编辑] 示例
struct A { A ( int ) {} operator int() const { return 0; } }; struct B { explicit B(int) {} explicit operator int() const { return 0; } }; int main() { // A is has no explicit ctor / conversion, everything is fine A a1 = 1; A a2 ( 2 ); A a3 { 3 }; int na1 = a1; int na2 = static_cast<int>( a1 ); B b1 = 1; // Error: implicit conversion from int to B B b2 ( 2 ); // OK: explicit constructor call B b3 { 3 }; // OK: explicit constructor call int nb1 = b2; // Error: implicit conversion from B to int int nb2 = static_cast<int>( b2 ); // OK: explicit cast }