什麼是C++中的引用變數?
引用變數是已存在變數的別名。它不能指向其他變數,應該在宣告時進行初始化,並且不能為NULL。運算子‘&’用於宣告引用變數。
以下是引用變數的語法。
datatype variable_name; // variable declaration datatype& refer_var = variable_name; // reference variable
其中,
datatype − 變數的資料型別,如int、char、float等。
variable_name − 這是使用者給出的變數名稱。
refer_var − 引用變數的名稱。
以下是引用變數的一個示例。
示例
#include <iostream> using namespace std; int main() { int a = 8; int& b = a; cout << "The variable a : " << a; cout << "\nThe reference variable r : " << b; return 0; }
輸出
The variable a : 8 The reference variable r : 8
在上面的程式中,聲明瞭一個整數型別的變數並用一個值對其進行了初始化。
int a = 8;
宣告變數b,它引用變數a。
int& b = a;
廣告