explicit 用来禁止隐式转换,它仅适用于构造函数。
关于隐式构造可以考虑下面的例子:
[C++] 纯文本查看 复制代码 #include "stdafx.h"
#include <iostream>
using namespace std;
class myclass {
int a;
public:
myclass(int x) { a = x; }
int geta() { return a; }
};
int _tmain(int argc, _TCHAR* argv[])
{
myclass ob1(4);
cout << ob1.geta() << endl;
myclass ob2 = 5; //隐式构造
cout << ob2.geta() << endl;
return 0;
}
运行输出:在上面的程序中,在声明出 ob2 这个对象时,我们使用的是隐式构造方式。一般的,如果在类中定义了一个只带有一个参数的构造函数,也就是隐式地创建了一个从参数的类型到类的类型的转换。对于这种情况,可以用 explicit 来禁止。比如将上面的构造函数声明为:explicit myclass(int x) { a = x; } ,那么 IDE (VS2010) 会在你录入程序时且当鼠标悬停在 myclass ob2 = 5; 中的 5 这个数字(5 的下面会有红色的波浪线标识)上时会看到提示:不存在从 "int" 转换到 "myclass" 的适当构造函数。 |