#include<iostream>
using namespace std;
void swap(int **a,int **b)
{
cout << endl;
cout << *a++ << " *a++ *****" << endl;
cout << a << " a *****" << endl;
cout << *a << " *a *****" << endl << endl;
cout << ++(*a) << " (*a)++ 33*****" << endl;
cout << a << " a 11*****" << endl;
cout << *a << " *a 22*****" << endl << endl;
}
void swap(int *a,int *b)
{
a++;
cout << a << " (int *a,int *b)" << endl;
}
void swap(int &a,int &b)
{
a++;
}
int main()
{
/* int c;
int d;
int *a=10;//error
// a = new int;
// *a=10;
int *b=&d;
*/
int a = 10;
int b = 20;
int *c;
int *d;
c = &a;
d = &b;
int **f = &c;
int **e = &d;
cout << *c << endl;
swap(*c,*d);
cout << *c << endl;
cout << "&c = " << &c << endl;
cout << "c = " << c << endl;
cout << "&a = " << &a << endl;
swap(c,d);
cout << "&a = " << &a << endl;
cout << "c = " << c << endl;
c ++;
//&a ++; error C2102: “&”要求左值
cout << "After c ++, &a = " << &a << endl;
cout << "After c ++, c = " << c << endl;
cout << "After c ++, &c = " << &c << endl;
cout << "After c ++, f = " << f << endl;
swap(f,e);
cout << "After swap(f,e), &a = " << &a << endl;
cout << "After swap(f,e), c = " << c << endl;
cout << "After swap(f,e), &c = " << &c << endl;
cout << "After swap(f,e), f = " << f << endl << endl << endl;
cout << &a << endl;
swap(&a,&b);
cout << &a << endl;
cout << a << endl;
swap(a,b);
cout << a << endl;
return 0;
}
输出:
10
11
&c = 002EFD04
c = 002EFD1C
&a = 002EFD1C
002EFD20 (int *a,int *b)
&a = 002EFD1C
c = 002EFD1C
After c ++, &a = 002EFD1C
After c ++, c = 002EFD20
After c ++, &c = 002EFD04
After c ++, f = 002EFD04
002EFD20 *a++ *****
002EFD08 a *****
CCCCCCCC *a *****
CCCCCCD0 (*a)++ 33*****
002EFD08 a 11*****
CCCCCCD0 *a 22*****
After swap(f,e), &a = 002EFD1C
After swap(f,e), c = 002EFD20
After swap(f,e), &c = 002EFD04
After swap(f,e), f = 002EFD04
002EFD1C
002EFD20 (int *a,int *b)
002EFD1C
11
12
引用与指针的区别:
1 引用被创建时必须被初始化,而指针不必
2 引用一旦被初始化则不能改变引用的对象,而指针可以随时改变指向的对象;
3 引用不能为NULL,而指针可以;
引用传递:
被调函数的形式参数虽然也作为局部变量在堆栈中开辟了内存空间,但是这时存放的是由主调函数放进来的实参变量的地址。被调函数对形参的任何操作都被处理成间接寻址,即通过堆栈中存放的地址访问主调函数中的实参变量。