C++ 中的 explicit 關鍵字是什麼意思?
C++ 中的 explicit 關鍵字用於標記建構函式,以不隱式轉換型別。例如,如果您有一個類 Foo −
class Foo { public: Foo(int n); // allocates n bytes to the Foo object Foo(const char *p); // initialize object with char *p };
現在如果你嘗試
Foo mystring = 'x';
字元 'x' 被隱式轉換為 int,然後將呼叫 Foo(int) 建構函式。但這不是預期結果。因此,為了防止這種情況並使程式碼不易出現錯誤,將建構函式定義為 explicit −
示例
class Foo { public: explicit Foo (int n); //allocate n bytes Foo(const char *p); // initialize with string p };
廣告