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

Unary Operator ใน C++


นิยาม

Unary operator ทำงานกับ operand เดียว สร้างค่าใหม่ รายการครบ:

Operatorคำอธิบาย
Indirection (*)Dereference pointer คืน l-value ที่ address
Address-of (&)ได้ address ของ operand (function designator หรือ l-value)
Unary plus (+)คืนค่า operand ต้องเป็น arithmetic type
Unary negation (-)ทำให้ค่าเป็นลบ arithmetic type ผลลัพธ์ไม่ใช่ lvalue
Logical negation (!)กลับความหมาย operand → bool
One's complement (~)Bitwise NOT integral type
Prefix increment (++)เพิ่ม 1 คืนค่าใหม่ l-value ไม่ใช่ const
Prefix decrement (--)ลด 1 คืนค่าใหม่ l-value ไม่ใช่ const
Cast ()Explicit type conversion
sizeofCompile-time size ของ operand
newDynamic memory allocation
deleteDeallocate dynamic memory

Associativity: right-to-left

ตัวอย่าง: - และ Cast

#include <iostream>
using namespace std;

int main() {
    int x;
    float y = 1.23;
    x = (int)y;  // cast
    x = -x;      // unary negation
    cout << x;
    return 0;
}

ผลลัพธ์

-1

หมายเหตุ: เนื้อหานี้ซ้ำกับ ID 1004083471