#include <iostream>
using namespace std;
int &counter()
{
static int n=0;
++n;
return n;
}
int main(int argc, char *argv[])
{
cout << counter() << endl;
cout << counter() << endl;
cout << counter() << endl;
counter()=100;
cout << counter() << endl;
cout << counter() << endl;
cout << counter() << endl;
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
1
2
3
101
102
103
返回一个int型的参照(引用)就好象返回了它的指针,你可以通过返回的int型的参照(引用)间接的修改它.例如
int glb_value=10;
int& g(int x)
{
... ...
return glb_value;
}
main()
{
int& tmpValue;
tmpValue = g(0);
tmpValue = 100; //实际上改的是glb_value的值,此时glb_value=100 !
}