搜尋此網誌

2025年8月5日星期二

Reference in C++

#include <iostream>

void incrementByReference(int& ref) {
    ref++;  // Directly increments the original variable
}

int main() {
    int value = 20;
    int& rValue = value;  // Declare a reference bound to 'value'
   
    std::cout << "Before: " << value << "\n";  // Prints 20
   
    incrementByReference(rValue);
   
    std::cout << "After:  " << value << "\n";  // Prints 21
   
    // References must be initialized and cannot be reseated
   
    return 0;
}

References in C++ act as true aliases for existing objects.

Once you bind a reference to an object, any operation through that reference directly

affects the original. There’s no extra indirection or separate storage - think of the

reference as a permanent nickname for the object.


Ideal for function parameters when you want to modify the caller’s variable.

value is the caller’s variable (actual parameter) in the main() function.

Microsoft and GitHub Copilot

沒有留言:

發佈留言