explicit用法,防止對(duì)象隱式被轉(zhuǎn)換。
例子一:隱式轉(zhuǎn)換
class C
{
public:
C ( int j );
int i;
};
C::C (int j)
{
i = j;
}
int main()
{
C c(0);
c = 5; //5被隱式轉(zhuǎn)換
}
c = 5 相當(dāng)于
C temp(5);// 實(shí)例化一個(gè)臨時(shí)對(duì)象,
c = temp; // 用 = 賦值
temp.C::~C(); // temp 的析構(gòu)函數(shù)被激活
如果類內(nèi)的成員是一個(gè)指針,這種隱式轉(zhuǎn)換是很危險(xiǎn)的。為了防止這種隱式轉(zhuǎn)換,我們把 C ( int j ); 改寫(xiě)為explicit C ( int j );即可。
這下編譯的時(shí)候,會(huì)不允許這種隱式的轉(zhuǎn)換,出現(xiàn)如下提示:
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)