C++ Reference 引用用法
来源:互联网 发布:投稿系统源码 编辑:程序博客网 时间:2024/05/20 23:59
1. Free Standing Reference
int y;
int& r = y; 定义一个引用的时候,必须初始化其值,否则编译器报错。
或者
const int& q = 12;
其相应的规则
1. A reference must be initialized when it is created. (Pointers
can be initialized at any time.)
2. Once a reference is initialized to an object, it cannot be
changed to refer to another object. (Pointers can be pointed to
another object at any time.)
3. You cannot have NULL references. You must always be able
to assume that a reference is connected to a legitimate piece
of storage.
2. 函数参数, 返回值
作为参数,改变参数的值也会影响到函数外的这个值。
作为返回值,要注意,返回值的作用空间。 不能返回local的值。
int& g(int& x) {
x++; // Same effect as in f()
return x; // Safe, outside this scope
}
(使用对象还是对象的引用)
http://blog.csdn.net/RichardYSteven/archive/2010/11/02/5981367.aspx
在上面这个帖子中,我研究了函数参数和返回值使用对象时的情况。那我们再来看看使用引用时的情况。
// Pass and return BY VALUE:
HowMany2 f(HowMany2 x) {
x.print("x argument inside f()");
cout << "Returning from f()" << endl;
return x;
}
// Pass BY REFERENCE and return BY VALUE:
HowMany2 f2(HowMany2& x) {
x.print("x argument inside f()");
cout << "Returning from f()" << endl;
return x;
}
// Pass BY REFERENCE and return BY REFERENCE:
HowMany2& f3(HowMany2& x) {
x.print("x argument inside f()");
cout << "Returning from f()" << endl;
return x;
}
上面是三种不同的形式。 得出的结论是,不管是参数还是返回值,只要是对象,都会调用一次拷贝构造函数。
也就是如果参数和返回值都是对象,那就会调用两次的拷贝构造函数。
=>所以,使用引用可以节约运行时间。
3. const reference
下面这两种形式是一样的。
void f(const A& a)
{
cout << a.a << endl;
}
void f1(A const & a)
{
cout << a.a << endl;
}
但是这样不可以, 真晕。
void f1(A& const a)
{
cout << a.a << endl;
}
如果函数参数不是const reference,那么如果传入一个const 的值,则会编译报错。
比如,如果传入一个const参数到上面的int& g(int& x),则会编译报错。
如果函数参数是const reference,那么函数体内,不能改变其值(built-in type),只能调用const函数,不能改变public成员。
4. Pointer references
指针引用,这个变态的
#include <iostream>
using namespace std;
void increment(int*& i) { i++; }
int main() {
int* i = 0;
cout << "i = " << i << endl;
increment(i);
cout << "i = " << i << endl;
}
- C++ Reference 引用用法
- 09 C++Reference引用的用法(学自Boolean)
- c++中引用(reference)用法剪辑
- C++中引用(reference)的用法详解
- reference引用
- reference :引用
- 引用(reference) &
- 引用Reference
- Object-C中对“引用(reference)”的理解
- Objective-C - ARC(Automatic Reference Counting)自动引用技术详解
- 引用 Invoke的用法(C#)
- C++reference~~~
- c++reference
- 引用(reference)类型
- C++中的引用(reference)
- PHP 中的引用(reference)
- C++中的引用(reference)
- reference count(引用计数)
- Eclipse中,对工作空间中的项目进行分组(在查询中,也可也选择这个分组)。
- 常见链表面试题
- insight,
- SQL2008不允许保存更改的表结构问题解决方法
- Linux下Java连接MySql数据库
- C++ Reference 引用用法
- VC之美化界面
- 2010 11-01
- 质数
- Android App Developers GUI Kits, Icons, Fonts and Tools
- Log4j使用总结
- 理解操作系统对程序的反馈:异常(Exception)和通知(Debug Event)【1】
- 理解操作系统对程序的反馈:异常(Exception)和通知(Debug Event)【2】
- Linux内核源码浅析——僵尸进程