Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

คีย์เวิร์ด explicit ใน C++ หมายถึงอะไร


explicit ใช้ติดหน้า constructor เพื่อ ป้องกัน implicit conversion (การแปลงแบบนัย)

ตัวอย่างปัญหา

class Foo {
public:
    Foo(int n);           // จัดสรร n ไบต์
    Foo(const char *p);   // initialize ด้วย string
};

หากเขียน Foo mystring = 'x'; ตัวอักษร 'x' จะถูกแปลงเป็น int (ASCII 120) แล้วเรียก Foo(int) ซึ่งไม่ใช่เจตนา

แก้ไขด้วย explicit

class Foo {
public:
    explicit Foo(int n);      // ป้องกัน implicit conversion จาก int
    Foo(const char *p);       // ยอมรับ implicit จาก const char*
};

ตอนนี้ Foo mystring = 'x'; จะ compile error บังคับให้เขียนชัดเจน: Foo mystring('x'); หรือ Foo mystring = Foo('x');