我们先来看一个简单的程序:

 

#include <iostream>
using namespace std;

int main()
{
	int &a = 1; // error
	cout << a << endl;

	return 1;
}

      显然, 这个程序是错误的。 如果编译器让它通过, 那后面的代码岂不是可以改变a的值了?

 

 

      如下代码才正确:

 

#include <iostream>
using namespace std;

int main()
{
	const int &a = 1; // ok, a和装1的空间同名
	cout << a << endl;

	return 1;
}


     再看看:

 

 

#include <iostream>
using namespace std;

void fun(int &x)
{
}

int main()
{
	int m = 1;
	fun(m); // ok

	fun(1); // error

	return 1;
}


     继续看:

 

 

#include <iostream>
using namespace std;

void fun(const int &x)
{
}

int main()
{
	int m = 1;
	fun(m); // ok

	fun(1); // ok

	return 1;
}


      可见, 在函数参数中, 使用常量引用非常重要。 因为函数有可能接受临时对象, 看看下面的例子, 就明白了:

 

 

#include <iostream>
using namespace std;

int test()
{
	return 1;
}

void fun(int &x)
{
}

int main()
{
	fun(test()); // error

	return 1;
}

 

 

#include <iostream>
using namespace std;

int test()
{
	return 1;
}

void fun(const int &x)
{
}

int main()
{
	fun(test()); // ok

	return 1;
}

      

     


本文转载:CSDN博客