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

Assignment Operators ใน C++


ประเภทการ Assign

  1. Simple assignment: e1 = e2 เก็บค่า e2 ไว้ใน e1
  2. Compound assignment: e1 op= e2 คำนวณ op แล้วเก็บผลใน e1

Simple Assignment Example

#include <iostream>
using namespace std;

int main() {
    int i;
    i = 10;  // simple assignment
    cout << i;
    return 0;
}
10

Compound Assignment Operators

รูปแบบ e1 op= e2 e1 = modifiable l-value (ไม่ใช่ const) e2 = arithmetic type หรือ pointer (ถ้า op เป็น +/-)

เทียบเท่า e1 = e1 op e2 แต่ e1 ประเมินครั้งเดียว

Operatorคำอธิบาย
*=คูณ e1 ด้วย e2
/=หาร e1 ด้วย e2
%=Modulus e1 ด้วย e2
+=บวก e2 เข้า e1
-=ลบ e2 จาก e1
<<=Left shift e1 ด้วย e2 bits
>>=Right shift e1 ด้วย e2 bits
&=Bitwise AND e1, e2
^=Bitwise XOR e1, e2
|=Bitwise OR e1, e2

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    int a = 3, b = 2;
    a += b; cout << a << endl;  // 5
    a -= b; cout << a << endl;  // 3
    a *= b; cout << a << endl;  // 6
    a /= b; cout << a << endl;  // 3
    return 0;
}

ผลลัพธ์

5
3
6
3

ข้อจำกัด

  • Enumerated type → error
  • Left pointer → right ต้องเป็น pointer หรือ 0
  • Left integral → right ห้ามเป็น pointer

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