您的位置:首页 > 编程语言 > C语言/C++

C++的常量引用

2014-11-06 23:20 218 查看
      我们先来看一个简单的程序:

#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;
}
      

     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: