c6011取消对null指针的引用_C++中的引用
當(dāng)變量聲明為引用時(shí),它將成為現(xiàn)有變量的替代名稱。通過在聲明中添加“&”,可以將變量聲明為引用。
#include 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; }輸出:
x = 20ref = 30應(yīng)用:
1. 修改函數(shù)中傳遞的參數(shù):如果函數(shù)收到對變量的引用,則可以修改變量的值。 例如,在以下程序變量中使用引用進(jìn)行交換。
#include 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; }輸出:
3 22. 避免復(fù)制大型結(jié)構(gòu):想象一個(gè)函數(shù)必須接收一個(gè)大型對象。如果我們不加引用地傳遞它,就會(huì)創(chuàng)建一個(gè)新的副本,這會(huì)導(dǎo)致CPU時(shí)間和內(nèi)存的浪費(fèi)。我們可以使用引用來避免這種情況。
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; }3. 在For Each循環(huán)中修改所有對象:我們可以使用For Each循環(huán)中的引用修改所有元素。
#include 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; }4. 在For-Each循環(huán)中避免對象的復(fù)制:我們可以在For-Each循環(huán)中使用引用,以避免在對象較大時(shí)復(fù)制單個(gè)對象。
#include using namespace std; int main() { vector 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; }引用與指針
引用和指針都可以用來更改一個(gè)函數(shù)在另一個(gè)函數(shù)中的局部變量。當(dāng)作為參數(shù)傳遞給函數(shù)或從函數(shù)返回時(shí),它們都還可以用于保存大對象的副本,以提高效率。
盡管有上述相似之處,但引用和指針之間仍存在以下差異。
可以將指針聲明為void,但引用永遠(yuǎn)不能為void。
例如:
int a = 10;void* aa = &a;. //it is validvoid &ar = a; // it is not valid引用沒有指針強(qiáng)大:
1)一旦創(chuàng)建了引用,以后就不能使它引用另一個(gè)對象;不能重新放置它。這通常是用指針完成的。
2)引用不能為NULL。指針通常被設(shè)置為NULL,以指示它們沒有指向任何有效的對象。
3)引用必須在聲明時(shí)進(jìn)行初始化。指針沒有這種限制。
由于上述限制,C++中的引用不能用于實(shí)現(xiàn)鏈接列表,樹等數(shù)據(jù)結(jié)構(gòu)。在Java中,引用沒有上述限制,可以用于實(shí)現(xiàn)所有數(shù)據(jù)結(jié)構(gòu)。引用在Java中更強(qiáng)大,這是Java不需要指針的主要原因。
引用更安全,更易于使用:
1)更安全:由于必須初始化引用,因此不太可能存在諸如野指針之類的野引用。
2)易于使用:引用不需要解引用運(yùn)算符即可訪問值。它們可以像普通變量一樣使用。僅在聲明時(shí)才需要“&”運(yùn)算符。另外,對象引用的成員可以使用點(diǎn)運(yùn)算符('.')訪問,這與需要使用箭頭運(yùn)算符(->)訪問成員的指針不同。
結(jié)合上述原因,在像復(fù)制構(gòu)造函數(shù)參數(shù)這樣的地方不能使用指針,必須使用引用傳遞副本構(gòu)造函數(shù)中的參數(shù)。類似地,必須使用引用來重載某些運(yùn)算符,例如++。
總結(jié)
以上是生活随笔為你收集整理的c6011取消对null指针的引用_C++中的引用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7 centos 源码安装samba_c
- 下一篇: @override报错_C++ 多态性: