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