1 -- 隱式類型轉換帶來的問題
我們首先看下面的這個例子,它可編譯也可執行,最終結果是“TDemo::print 55”。有理由推斷,執行個體化一個對象時,編譯器自動將55這個整數轉換成了“class TDemo”。類TDemo定義了一個單參數建構函式,而C++標準中,“單參數建構函式,可以完成從形參到該類型的一個隱式轉換”,所以編譯器能夠完成從int類型到TDemo的類型轉換。
#include <iostream>class TDemo{public:TDemo(int num);void print() const { std::cout 2 -- 禁止隱式類型轉換調用“TDemo demo = 55”實際就是“TDemo demo = TDemo(55)”,編譯器隱式調用單參數建構函式產生一個TDemo臨時對象,然後將該臨時對象複製給demo變數。有時候並不希望編譯器隱瞞我們,“私自”完成進行這種隱式轉換,在需要轉換的時候需要程式員明確使用顯示轉換,這樣寫下來的程式簡單清晰,還可以規避很多由隱式轉換引發的歧義和錯誤。這時就可以使用關鍵字explicit來禁止在需要隱式轉換的上下文中使用單參數建構函式。
修改上面例子程式,單參數建構函式使用explicit來修飾,再次編譯器後,發現會提示錯誤:“error: conversion from `int' to non-scalar type `TDemo' requested”,也就禁止了隱式類型轉換。#include <iostream>class TDemo{public:explicit TDemo(int num);void print() const { std::cout 3 -- 使用explicit關鍵字注意事項explicit關鍵字只能用於類內部的建構函式聲明上,在類的定義體外部所做的定義上不在重複它。也就是下面兩種方式都是錯誤的:
class TDemo{public:TDemo(int num);};//error: only declarations of constructors can be `explicit'explicit TDemo::TDemo(int num):i_num(num){}
class TDemo{public:explicit TDemo(int num);};//error: only declarations of constructors can be `explicit'explicit TDemo::TDemo(int num):i_num(num){}