explicit

    技术2022-05-20  46

    class Test1 { public: Test1(int n){num=n;} private: int num; }; class Test2 { public: explicit Test2(int n){num = n;} private: int num; }; int main(int argc, char* argv[]) { Test1 t1 = 12; Test2 t2 = 12; //编译错误error C2440: 'initializing' : cannot convert from 'const int' to 'class Test2' //No constructor could take the source type, or constructor overload resolution was ambiguo Test2 t3(12); return 0; }

    C++提供了关键字explicit可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生。声明为explicit的构造函数不能在隐式转换中使用。

    C++中, 一个参数的构造函数(或者除了第一个参数外其余参数都有默认值的多参构造函数), 承担了两个角色。 1 是个构造器 2 是个默认且隐含的类型转换操作符。

      所以, 有时候在我们写下如 AAA = XXX, 这样的代码, 且恰好XXX的类型正好是AAA单参数构造器的参数类型, 这时候编译器就自动调用这个构造器,创建一个AAA的对象。

      这样看起来好象很酷, 很方便。 但在某些情况下(见下面权威的例子), 却违背了我们(程序员)的本意。 这时候就要在这个构造器前面加上explicit修饰, 指定这个构造器只能被明确的调用,使用, 不能作为类型转换操作符被隐含的使用。 呵呵, 看来还是光明正大些比较好。

     


    最新回复(0)