1 引用的基本使用
int main ( int argc, char const * argv[ ] )
{ int a = 10 ; int & b = a; cout << "a = " << a << endl; cout << "b = " << b << endl; b = 100 ; cout << "a = " << a << endl; cout << "b = " << b << endl; return 0 ;
}
2 引用注意事项
int main ( int argc, char const * argv[ ] )
{ int a = 10 ; int b = 20 ; int & r = a; r = b; r = 30 ; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "r = " << r << endl; return 0 ;
}
3 引用做函数参数
void swap01 ( int a, int b) { int temp = a; a = b; b = temp;
}
void swap02 ( int * a, int * b) { int temp = * a; * a = * b; * b = temp;
}
void swap03 ( int & a, int & b) { int temp = a; a = b; b = temp;
} int main ( int argc, char const * argv[ ] )
{ int a = 10 ; int b = 20 ; cout << "交换前:a = " << a << " b = " << b << endl; swap01 ( a, b) ; cout << "值传递 交换后:a = " << a << " b = " << b << endl; swap02 ( & a, & b) ; cout << "地址传递 交换后:a = " << a << " b = " << b << endl; swap03 ( a, b) ; cout << "引用传递 交换后:a = " << a << " b = " << b << endl; return 0 ;
}
4. 引用做函数的返回值
# include <iostream>
using namespace std;
int & test01 ( ) { int a = 10 ; return a;
}
int & test02 ( ) { static int a = 10 ; cout << & a << endl; return a;
} int & test03 ( ) { static int a = 20 ; cout << "test03 " << & a << endl; return a;
} int main ( int argc, char const * argv[ ] )
{ int & b = test01 ( ) ; cout << & b << endl; int & c = test02 ( ) ; cout << & c << endl; cout << c << endl; c = test03 ( ) ; cout << c << endl; cout << & c << endl; test02 ( ) = 100 ; cout << "函数调用作为左值 " << c << endl; return 0 ;
}
5. 引用的本质
# include <iostream>
using namespace std;
void func ( int & ref) { ref = 100 ;
} int main ( int argc, char const * argv[ ] )
{ int a = 10 ; int & ref = a; ref = 20 ; cout << "a = " << a << endl; cout << "ref = " << ref << endl; func ( a) ; cout << "a = " << a << endl; return 0 ;
}
6 常量引用
/ #include < iostream>
using namespace std;
void func ( const int & ref) { cout << "ref " << ref << endl;
} int main ( int argc, char const * argv[ ] )
{ int a = 10 ; const int & ref = 10 ; cout << ref << endl; func ( a) ; a = 100 ; func ( a) ; return 0 ;
}