调用“TDemo demo = 55”实际就是“TDemo demo = TDemo(55)”,编译器隐式调用单参数构造函数生成一个TDemo临时对象,然后将该临时对象复制给demo变量。有时候并不希望编译器隐瞒我们,“私自”完成进行这种隐式转换,在需要转换的时候需要程序员明确使用显示转换,这样写下来的程序简单清晰,还可以规避很多由隐式转换引发的歧义和错误。这时就可以使用关键字explicit来禁止在需要隐式转换的上下文中使用单参数构造函数。 修改上面例子程序,单参数构造函数使用explicit来修饰,再次编译程序后,发现会提示错误:“error: conversion from int' to non-scalar type TDemo’ requested”,也就禁止了隐式类型转换。
//error: only declarations of constructors can be `explicit' explicitTDemo::TDemo(int num):i_num(num){} classTDemo { public: explicitTDemo(int num); };
//error: only declarations of constructors can be `explicit' explicitTDemo::TDemo(int num):i_num(num){}