ใน C เราไม่สามารถใช้ชื่อฟังก์ชันที่ด้านซ้ายมือของนิพจน์ได้ ใน C ++ เราสามารถใช้มันแบบนั้นได้ ซึ่งสามารถทำได้โดยฟังก์ชันบางอย่างที่คืนค่าตัวแปรอ้างอิงบางส่วน
ฟังก์ชัน C++ สามารถคืนค่าการอ้างอิงในลักษณะเดียวกับที่ส่งกลับตัวชี้
เมื่อฟังก์ชันส่งคืนการอ้างอิง ฟังก์ชันจะส่งกลับตัวชี้โดยนัยเป็นค่าที่ส่งคืน วิธีนี้สามารถใช้ฟังก์ชันทางด้านซ้ายของคำสั่งมอบหมายได้ Forexample พิจารณาโปรแกรมง่ายๆ นี้ -
ตัวอย่าง
#include <iostream>
#include <ctime>
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double& setValues( int i ) {
return vals[i]; // return a reference to the ith element
}
// main function to call above defined function.
int main () {
cout << "Value before change" << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
setValues(1) = 20.23; // change 2nd element
setValues(3) = 70.8; // change 4th element
cout << "Value after change" << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
return 0;
} ผลลัพธ์
Value before change vals[0] = 10.1 vals[1] = 12.6 vals[2] = 33.1 vals[3] = 24.1 vals[4] = 50 Value after change vals[0] = 10.1 vals[1] = 20.23 vals[2] = 33.1 vals[3] = 70.8 vals[4] = 50
เมื่อส่งคืนการอ้างอิง ให้ระวังว่าอ็อบเจ็กต์ที่อ้างอิงถึงไม่ goout ของขอบเขต ดังนั้นจึงไม่ถูกกฎหมายที่จะส่งคืนการอ้างอิงไปยัง var ในพื้นที่ แต่คุณสามารถคืนค่าอ้างอิงของตัวแปรสแตติกได้เสมอ
int& func() {
int q;
//! return q; // Compile time error
static int x;
return x; // Safe, x lives outside this scope
}