นิยาม
Unary operator คือออเปอเรเตอร์ที่ทำงานกับออเปอแรนด์เพียงตัวเดียวเพื่อสร้างค่าใหม่ ออเปอเรเตอร์ Unary ใน C++ มีดังนี้:
| ออเปอเรเตอร์ | คำอธิบาย |
|---|---|
| Indirection (*) | ทำงานกับตัวแปร pointer คืนค่า l-value เทียบเท่าค่าที่ address นี้ เรียกว่า "dereferencing" |
| Address-of (&) | คืน address ของ operand ต้องเป็น function designator หรือ l-value ที่ไม่ใช่ bit field และไม่ได้ประกาศ register |
| Unary plus (+) | คืนค่าของ operand ต้องเป็น arithmetic type |
| Unary negation (-) | ทำให้ค่า operand เป็นลบ ต้องเป็น arithmetic type ผลลัพธ์ไม่ใช่ lvalue |
| Logical negation (!) | กลับความหมายของ operand ต้องเป็น arithmetic หรือ pointer type แปลงเป็น bool อัตโนมัติ |
| One's complement (~) | Bitwise complement สร้าง one's complement ของ operand ต้องเป็น integral type |
| Prefix increment (++) | เพิ่มค่า operand 1 ค่าที่เพิ่มแล้วคือผลลัพธ์ ต้องเป็น l-value ไม่ใช่ const ผลลัพธ์เป็น l-value |
| Prefix decrement (--) | ลดค่า operand 1 ค่าที่ลดแล้วคือผลลัพธ์ ต้องเป็น l-value ไม่ใช่ const ผลลัพธ์เป็น l-value |
| Cast operator () | แปลงชนิดข้อมูลอย่างชัดเจน (explicit conversion) ในสถานการณ์เฉพาะ |
| sizeof | Compile-time unary operator คำนวณขนาดของ operand |
| new | จัดสรรหน่วยความจำแบบไดนามิก |
| delete | ปล่อยหน่วยความจำที่จัดสรรแบบไดนามิก |
ออเปอเรเตอร์เหล่านี้มี associativity แบบ right-to-left นิพจน์ Unary โดยทั่วไปเกี่ยวข้องกับ syntax ที่วางก่อน postfix หรือ primary expression
ตัวอย่าง: ออเปอเรเตอร์ - และ Cast
#include <iostream>
using namespace std;
int main() {
int x;
float y = 1.23;
x = (int) y; // Cast operator
x = -x; // Unary negation
cout << x;
return 0;
}
ผลลัพธ์
-1