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

วิธีส่งออบเจ็กต์ไปยังฟังก์ชันใน C++ (Pass Objects to Functions)


มี 5 วิธีส่งออบเจ็กต์ไปฟังก์ชัน (สมมติคลาส X, ฟังก์ชัน fun):

1. Pass by Value

สร้าง shallow copy ใน scope ฟังก์ชัน การแก้ไขไม่ส่งผลต่อ object ต้นฉบับ

void fun(X x);  // Declaration
X x; fun(x);      // Calling

2. Pass by Reference

ส่ง reference ไป ฟังก์ชันแก้ไข object ต้นฉบับได้ ไม่สร้าง copy

void fun(X &x);
X x; fun(x);

3. Pass by Const Reference

ส่ง const reference ฟังก์ชันอ่านอย่างเดียว (read-only) ไม่สร้าง copy ใช้เมื่อต้องการประสิทธิภาพแต่ไม่อยากให้แก้ไข

void fun(X const &x);
X x; fun(x);

4. Pass by Const Pointer

ส่ง const pointer ไม่สามารถเปลี่ยน pointer เองได้ (แต่ object ชี้ไปอาจแก้ได้ถ้าไม่ const)

void fun(X const *x);
X x; fun(&x);

5. Pass by Pointer (Non-const)

คล้าย pass by reference แต่ใช้ pointer syntax

void fun(X *x);
X x; fun(&x);

แนวทางเลือก: ใช้ const reference เป็นค่าเริ่มต้นสำหรับ input parameters ใช้ reference/pointer เมื่อต้อง modify