C++ 引用的属性和特别之处

引用的属性和特别之处:

#include<iostream>
double cube(double a);
double refcube(double &ra);
int main()
{
    
    
	using namespace std;
	double x = 3.0;
	cout << cube(x);
	cout << " = cube of " << x << endl;
	cout << refcube(x);
	cout << " = cube of " << x << endl;
	return 0;
}
double cube(double a)
{
    
    
	a *= a * a;
	return a;
}
double refcube(double &ra)
{
    
    
	ra *= ra * ra;
	return ra;
}

程序的输出为:

27 = cube of 3
27 = cube of 27

从程序的输出可以看出,refcube()函数修改了main()中x的值,而cube()不会影响x,可见引用就是使用了变量本身,如果意图使用引用,又不想对原始进行修改,则应该使用常量引用,例如:

double refcube(const double& ra);

这样当编译器发现函数试图修改原始变量时将显示错误信息。
临时变量、引用参数和const:
如果实参与引用参数不匹配,C++将生成临时变量,仅当参数为const引用时,C++才允许这样做。
应尽量使用const的理由:

  • 使用const可以避免无意中修改数据的编程错误;
  • 使用const使函数能够处理cosnt和非const实参,否则将只能接受非const数据;
  • 使用const引用使函数能够正确生成并使用临时变量;

猜你喜欢

转载自blog.csdn.net/weixin_42105843/article/details/118483439
今日推荐