C++中的引用

C++中的引用

当变量声明为引用时,它将成为现有变量的替代名称。通过在声明中添加“&”,可以将变量声明为引用。

<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)易于使用:引用不需要解引用运算符即可访问值。它们可以像普通变量一样使用。仅在声明时才需要“&”运算符。另外,对象引用的成员可以使用点运算符('.')访问,这与需要使用箭头运算符(->)访问成员的指针不同。

结合上述原因,在像复制构造函数参数这样的地方不能使用指针,必须使用引用传递副本构造函数中的参数。类似地,必须使用引用来重载某些运算符,例如++。


分享到:


相關文章: