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

你可能感兴趣的:(C++,c,C#,F#)