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

Overloading Unary Operator ใน C++


Operator Overloading

Keyword operator ประกาศฟังก์ชันระบุความหมายของ Operator-symbol เมื่อใช้กับ Instances ของ Class ให้ Operator มีความหมายมากกว่าหนึ่ง (Overload) Compiler แยกความหมายจากชนิดของ Operands

Unary Operators

ทำงานกับ Single Operand ตัวอย่าง:

  • Increment (++) และ Decrement (--)
  • Unary Minus (-)
  • Logical Not (!)

Unary Operators ทำงานบน Object ที่ถูกเรียก ปกติอยู่ด้านซ้าย (Prefix): !obj, -obj, ++obj แต่บางครั้งเป็น Postfix: obj++, obj--

ตัวอย่าง: Overload Bang (!) Operator แบบ Prefix

#include <iostream>
using namespace std;

class Distance {
private:
    int feet;   // 0 to infinite
    int inches; // 0 to 12
public:
    Distance(int f, int i) { feet = f; inches = i; }
    void display() { cout << "F: " << feet << " I:" << inches << endl; }
    // Overloaded ! operator
    Distance operator!() {
        feet = -feet;
        inches = -inches;
        return Distance(feet, inches);
    }
};

int main() {
    Distance D1(3, 4), D2(-1, 10);
    !D1; D1.display();  // F: -3 I:-4
    !D2; D2.display();  // F: 1 I:-10
    return 0;
}

Output

F: -3 I:-4
F: 1 I:-10