系列文章目录
前言
一、引用
函数引用,与变量名指向相同的内存,不需要向指针那样需要申请内存
但引用必须要进行初始化
函数代码如下:
#include <iostream>
#include <cmath>
using namespace std;
float norm_l1(float x, float y); //declaration
float norm_l2(float x, float y); //declaration
float (&norm_ref)(float x, float y) = norm_l1; //norm_ref is a function reference
int main()
{
cout << "L1 norm of (-3, 4) = " << norm_ref(-3, 4) << endl;
return 0;
}
float norm_l1(float x, float y)
{
return fabs(x) + fabs(y);
}
float norm_l2(float x, float y)
{
return sqrt(x * x + y * y);
}
2.简单示例
代码如下:
#include <iostream>
using namespace std;
int main()
{
int num = 0;
// 定义变量名的别名-引用
int & num_ref = num;
cout << "num = " << num << endl;
num_ref = 10;
cout << "num = " << num << endl;
return 0;
}
// num = 0
// num = 10
2.参数引用
代码如下(示例):
#include <iostream>
#include <float.h>
struct Matrix
{
int rows;
int cols;
float * pData;
};
float matrix_max(const struct Matrix & mat)
{
float max = FLT_MIN;
//find max value of mat
for(int r = 0; r < mat.rows; r++)
for (int c = 0; c < mat.cols; c++)
{
float val = mat.pData[ r * mat.cols + c];
max = ( max > val ? max : val);
}
return max;
}
int main()
{
using namespace std;
Matrix matA = {3,4};
matA.pData = new float[matA.rows * matA.cols]{1.f, 2.f, 3.f};
Matrix matB = {4,8};
matB.pData = new float[matB.rows * matB.cols]{10.f, 20.f, 30.f};
Matrix matC = {4, 2};
matC.pData = new float[matC.rows * matC.cols]{100.f, 200.f, 300.f};
// some operations on the matrices
float maxa = matrix_max(matA);
float maxb = matrix_max(matB);
float maxc = matrix_max(matC);
cout << "max(matA) = " << maxa << endl;
cout << "max(matB) = " << maxb << endl;
cout << "max(matC) = " << maxc << endl;
delete [] matA.pData;
delete [] matB.pData;
delete [] matC.pData;
return 0;
}
总结
// 引用是变量的别名,对应同一个数据;
// 指针与引用的区别,指针创建变量、申请内存,引用声明时必须初始化;
// 引用更安全,具体到特定对象,不会乱指;没有copy数据,通过引用来访问数据内存
// 会修改外部变量,加const 避免数据修改