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

การ Overload Unary Operator ใน C++ คืออะไร?

Unary operators ทำงานบน operand เดียว ตัวอย่าง unary operators -

  • Increment (++) และ Decrement (--) operators
  • Unary minus (-) operator
  • Logical not (!) operator

Unary operators ทำงานบน object ที่ถูกเรียก และปกติ operator ปรากทางซ้ายของ object เช่น !obj, -obj, ++obj แต่บางครั้งใช้เป็น postfix ได้ เช่น obj++ หรือ obj--

ตัวอย่างต่อไปนี้อธิบายการ overload bang (!) operator สำหรับ prefix usage -

ตัวอย่าง

#include <iostream>
using namespace std;
class Distance {
private:
    int feet;   // 0 to infinite
    int inches; // 0 to 12
public:
    // Constructor
    Distance(int f, int i) {
        feet = f;
        inches = i;
    }
    // method to display distance
    void display() {
        cout << "F: " << feet << " I:" << inches << endl;
    }
    // overloaded bang(!) operator
    Distance operator!() {
        feet = -feet;
        inches = -inches;
        return Distance(feet, inches);
    }
};
int main() {
    Distance D1(3, 4), D2(-1, 10);
    !D1;
    D1.display(); // display D1
    !D2;
    D2.display(); // display D2
    return 0;
}

ผลลัพธ์

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