C++ References

Section 5.5 of The C++ Programming Language (Special 3rd Edition) has a precise explanation about references. I use the following code to help me understand it.

 

 

#include <iostream>
#include <vector>
using namespace std;

void a() {
  cout << "a-----------------" << endl;
  int i = 1;
  int& r = i;
  int x = r;

  r = 2;
  cout << "i: " << i << endl;
  cout << "x: " << x << endl;
}

void b() {
  cout << "b--------------------" << endl;
  int ii = 0;
  int& rr = ii;
  rr++;
  int* pp = &rr;

  cout << "ii: " << ii << endl;
}

void c()  {
  // can't be compiled
  //double& dr = 1;

  const double& cdr = 1;
}

void increment(int& aa) {
  aa++;
}

void d() {
  cout << "d------------------" << endl;
  int i = 1;
  increment(i);
  cout << "i: " << i << endl;
}

int my_next(int p) {
  return p + 1;
}

void incr(int* p) {
  (*p)++;
}

void e() {
  cout << "e-----------------" << endl;
  int x = 1;
  increment(x);
  x = my_next(x);
  incr(&x);
  cout << "x: " << x << endl;
}

struct Pair {
  string name;
  double val;
};

vector<Pair> pairs;

double& value(const string& s) {
  for (int i = 0; i < pairs.size(); i++)
    if (s == pairs[i].name)
      return pairs[i].val;

  Pair p = {s, 0};
  pairs.push_back(p);

  return pairs[pairs.size() - 1].val;
}

void f() {
  string buf[] = {"aa", "bb", "bb", "aa", "aa", "bb", "aa", "aa"};

  for (int i = 0; i < 8; i++)
    value(buf[i])++;

  for (vector<Pair>::const_iterator p = p = pairs.begin(); p != pairs.end(); ++p)
    cout << p->name << ": " << p->val << endl;
}

int global = 10;

int& back() {
  return global;
}

void g() {
  cout << "g-------------------" << endl;
  int value = back();
  value++;
  cout << "value: " << value << ", global: " << global << endl;

  int& ref = back();
  ref++;
  cout << "ref: " << value << ", global: " << global << endl;
}

int main(int argc, const char *argv[]) {
  a(); 
  b();
  c();
  d();
  e();
  f();
  g();
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值