當變量聲明為引用時,它將成為現有變量的替代名稱。通過在聲明中添加“&”,可以將變量聲明為引用。
<code>#include<iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << endl ;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl ;
return 0;
} /<iostream>/<code>
輸出:
<code>x = 20
ref = 30/<code>
應用:
1. 修改函數中傳遞的參數:如果函數收到對變量的引用,則可以修改變量的值。 例如,在以下程序變量中使用引用進行交換。
<code>#include<iostream>
using namespace std;
void swap (int& first, int& second)
{
int temp = first;
first = second;
second = temp;
}
int main()
{
int a = 2, b = 3;
swap( a, b );
cout << a << " " << b;
return 0;
} /<iostream>/<code>
輸出:
<code>3 2 /<code>
2. 避免複製大型結構:想象一個函數必須接收一個大型對象。如果我們不加引用地傳遞它,就會創建一個新的副本,這會導致CPU時間和內存的浪費。我們可以使用引用來避免這種情況。
<code>struct Student {
string name;
string address;
int rollNo;
}
// If we remove & in below function, a new
// copy of the student object is created.
// We use const to avoid accidental updates
// in the function as the purpose of the function
// is to print s only.
void print(const Student &s)
{
cout << s.name << " " << s.address << " " << s.rollNo;
} /<code>
3. 在For Each循環中修改所有對象:我們可以使用For Each循環中的引用修改所有元素。
<code>#include <bits>
using namespace std;
int main()
{
vector vect{ 10, 20, 30, 40 };
// We can modify elements if we
// use reference
for (int &x : vect)
x = x + 5;
// Printing elements
for (int x : vect)
cout << x << " ";
return 0;
} /<bits>/<code>
4. 在For-Each循環中避免對象的複製:我們可以在For-Each循環中使用引用,以避免在對象較大時複製單個對象。
<code>#include <bits>
using namespace std;
int main()
{
vector<string> vect{"geeksforgeeks practice",
"geeksforgeeks write",
"geeksforgeeks ide"};
// We avoid copy of the whole string
// object by using reference.
for (const auto &x : vect)
cout << x << endl;
return 0;
} /<string>/<bits>/<code>
引用與指針
引用和指針都可以用來更改一個函數在另一個函數中的局部變量。當作為參數傳遞給函數或從函數返回時,它們都還可以用於保存大對象的副本,以提高效率。
儘管有上述相似之處,但引用和指針之間仍存在以下差異。
可以將指針聲明為void,但引用永遠不能為void。
例如:
<code>int a = 10;
void* aa = &a;. //it is valid
void &ar = a; // it is not valid/<code>
引用沒有指針強大:
1)一旦創建了引用,以後就不能使它引用另一個對象;不能重新放置它。這通常是用指針完成的。
2)引用不能為NULL。指針通常被設置為NULL,以指示它們沒有指向任何有效的對象。
3)引用必須在聲明時進行初始化。指針沒有這種限制。
由於上述限制,C++中的引用不能用於實現鏈接列表,樹等數據結構。在Java中,引用沒有上述限制,可以用於實現所有數據結構。引用在Java中更強大,這是Java不需要指針的主要原因。
引用更安全,更易於使用:
1)更安全:由於必須初始化引用,因此不太可能存在諸如野指針之類的野引用。
2)易於使用:引用不需要解引用運算符即可訪問值。它們可以像普通變量一樣使用。僅在聲明時才需要“&”運算符。另外,對象引用的成員可以使用點運算符('.')訪問,這與需要使用箭頭運算符(->)訪問成員的指針不同。
結合上述原因,在像複製構造函數參數這樣的地方不能使用指針,必須使用引用傳遞副本構造函數中的參數。類似地,必須使用引用來重載某些運算符,例如++。