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; }
相关文章推荐
- C++常量和引用数据成员的初始化
- c++ 类中常量成员,和引用成员初始化
- C++常量引用作为函数参数的例子
- [C++学习笔记]--常量对象、常量成员函数和常引用
- c++ 对象/const对象/const引用/const指针/顶层const/底层const/ constexpr及常量表达式
- 常量函数、常量引用参数、常量引用返回值[C++]
- C++ 类中特殊成员变量(常量、静态、引用)的初始化方法
- C++引用,常量优化,四种类型转换符
- C++标准的规定:非常量的引用不能指向临时对象(转载)
- C++中静态变量、常量、静态整型常量、静态非整型常量、引用变量的初始化方法
- 常量函数、常量引用参数、常量引用返回值[C++]
- C++中常量引用
- C++ 常量指针或者常量引用作为函数参数传递的原因
- c++基础三(基本知识-变量,常量,枚举,引用)
- 常量函数、常量引用参数、常量引用返回值[C++]
- C++中传值方式传参与引用常量传参的使用规则
- c++ 类中常量成员,和引用成员初始化
- C++的常量引用
- C++特殊成员变量(静态、常量、引用)的初始化方法
- C++中常量引用(const reference)