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

ใช้ฟังก์ชันด้านซ้ายของ expression ใน C และ C++ ได้ไหม


ใน C ไม่สามารถใช้ชื่อฟังก์ชันด้านซ้ายของ expression ได้ ใน C++ ทำได้ โดยฟังก์ชันที่คืน reference variable

C++ function สามารถคืน reference ได้คล้ายกับการคืน pointer

เมื่อฟังก์ชันคืน reference มันคืน implicit pointer ไปยัง return value วิธีนี้ ฟังก์ชันสามารถใช้ด้านซ้ายของ assignment statement ได้ ตัวอย่าง:

ตัวอย่าง

#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

เมื่อคืน reference ต้องระวัง object ที่อ้างถึงไม่ออกนอก scope จึงไม่ถูกต้องที่จะคืน reference ของ local variable แต่สามารถคืน reference ของ static variable ได้เสมอ

int& func() {    int q;    //! return q; // Compile time error    static int x;    return x; // Safe, x lives outside this scope }