电竞比分网-中国电竞赛事及体育赛事平台

分享

C++中 explicit 關(guān)鍵字作用詳解

 My鏡像站 2011-11-16

【前言】

    今天遇到了個(gè)問(wèn)題,被人問(wèn)及 explicit 作用的時(shí)候,想不起來(lái)了C++ 中 explicit 關(guān)鍵字作用詳解 - 曹操(小魚(yú)兒) - 系統(tǒng)分析師 曹操。因此重新溫習(xí)了一下,詳細(xì)描述如下:

【正文】

    簡(jiǎn)單的說(shuō),就是類的構(gòu)造函數(shù)禁止隱式類型轉(zhuǎn)換。先看一看微軟大哥是如何說(shuō)的:

This keyword is a declaration specifier that can only be applied to inclass constructor declarations. Constructors declared explicit will not be considered for implicit conversions. For example:

class X {  public:     explicit X(int);      //legal     explicit X(double) {   //legal        // ...     }  };    explicit X::X(int) {}      //illegal

An explicit constructor cannot take part in implicit conversions. It can only be used to explicitly construct an object. For example, with the class declared above:

void f(X) {}  void g(int I) {     f(i);      // will cause error  }  void h() {     X x1(1);      // legal  }

The function call f(i) fails because there is no available implicit conversion from int to X.

Note   It is meaningless to apply explicit to constructors with multiple arguments, since such constructors cannot take part in implicit conversions.

總結(jié)一下,大致意思就是:

(1) explicit 只能在類的內(nèi)部使用,不能在外面聲明。

(2)聲明了explicit以后,就不允許隱式轉(zhuǎn)換了。

(3)explicit對(duì)于多個(gè)參數(shù)的構(gòu)造函數(shù)無(wú)任何意義。

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多