explicit用法,防止對象隱式被轉換。
例子一:隱式轉換
class C
{
public:
C ( int j );
int i;
};
C::C (int j)
{
i = j;
}
int main()
{
C c(0);
c = 5; //5被隱式轉換
}
c = 5 相當于
C temp(5);// 實例化一個臨時對象,
c = temp; // 用 = 賦值
temp.C::~C(); // temp 的析構函數被激活
如果類內的成員是一個指針,這種隱式轉換是很危險的。為了防止這種隱式轉換,我們把 C ( int j ); 改寫為explicit C ( int j );即可。
這下編譯的時候,會不允許這種隱式的轉換,出現如下提示:
Compiling
test.cpp
D:\DATUM\DATUM\PROJECT\Test_muable\test.cpp(14) : error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'const int' (or there is no acceptable conversion)
Error executing cl.exe.
Test_muable.exe - 1 error(s), 0 warning(s)