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

การใช้ explicit Keyword ใน C++

explicit ป้องกัน implicit conversion จาก constructor ที่รับ argument เดียว (converting constructor)

โดยไม่มี explicit (Implicit Conversion)

class Point {
    double x, y;
public:
    Point(double a=0, double b=0) : x(a), y(b) {}
    bool operator==(Point p) { return x==p.x && y==p.y; }
};

int main() {
    Point p(5, 0);
    if (p == 5) cout << "Same"; // OK: 5 แปลงเป็น Point(5,0) อัตโนมัติ
}

มี explicit (บังคับ explicit conversion)

class Point {
    double x, y;
public:
    explicit Point(double a=0, double b=0) : x(a), y(b) {}
    bool operator==(Point p) { return x==p.x && y==p.y; }
};

int main() {
    Point p(5, 0);
    if (p == 5) cout << "Same"; // Error: no match for operator==(Point, int)
    if (p == (Point)5) cout << "Same"; // OK: explicit cast
}

ใช้ explicit เพื่อป้องกัน conversion ที่ไม่ได้ตั้งใจ ทำให้โค้ดปลอดภัยและอ่านง่ายกว่า