// 示例代码:C++中&的用法
#include <iostream>
using namespace std;
// 1. 引用作为函数参数
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
// 2. 引用返回值
int& getReference(int arr[], int index) {
return arr[index];
}
// 3. 常量引用
void print(const int &value) {
cout << value << endl;
}
int main() {
int x = 5, y = 10;
// 使用引用交换两个变量的值
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
// 使用引用返回数组元素并修改
int arr[] = {1, 2, 3};
getReference(arr, 1) = 100;
cout << "Array after modification: ";
for (int i = 0; i < 3; i++) {
cout << arr[i] << " ";
}
cout << endl;
// 使用常量引用避免拷贝
int z = 42;
print(z);
return 0;
}
引用作为函数参数:
void swap(int &a, int &b)
:通过引用传递参数,函数内部对参数的修改会反映到调用者的实际参数上。这里swap
函数可以交换两个整数的值。引用返回值:
int& getReference(int arr[], int index)
:返回一个数组元素的引用,允许在函数外部直接修改该元素的值。常量引用:
void print(const int &value)
:使用const
关键字声明常量引用,防止函数内部修改传入的参数,同时避免了不必要的拷贝操作,提高性能。以上示例展示了&
在C++中的几种常见用法。
上一篇:c++ chrono
下一篇:c++ extern关键字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站