在打平衡二叉樹時,看別人代碼用到了指針的引用,因?yàn)橹皼]有用過我以為是他多此一舉,但是并不是.
首先是函數(shù)傳遞指針
#include<iostream>
using namespace std;
int a = 1;
void test(int *p)
{
p = &a;
}
int main()
{
int d = 2;
int *p = &d;
cout << *p << endl;
test(p);
cout << *p << endl;
}
運(yùn)行結(jié)果:

1.png
在正常情況下我們想要的結(jié)果是2 1
但是輸出卻是2 2;
因?yàn)橹羔榩傳遞到test函數(shù)時接受的是指針,
改變的是形參,而實(shí)參main中指針p沒有發(fā)生變化.
傳遞指針的指針
#include<iostream>
using namespace std;
int a = 1;
void test(int **p)
{
*p = &a;//一次解析,是被指向指針的指針
}
int main()
{
int d = 2;
int *p = &d;
cout << *p << endl;
test(&p);//將*p的地址穿入test
cout << *p << endl;
}
運(yùn)行結(jié)果:

2.png
這樣結(jié)果就對了.但是兩次解析讓人頭暈.
#include<iostream>
using namespace std;
int a = 1;
void test(int *&p)//對main中*p的引用
{
p = &a;
}
int main()
{
int d = 2;
int *p = &d;
cout << *p << endl;
test(p);
cout << *p << endl;
}
運(yùn)行結(jié)果: 2 1
想起來c++ primer書上剛講引用的例子
string a="i''m a good boy"
for(auto s:a)
toupper(s);
cout<<a<<endl;
這樣a不會變,如果用auto &s的話就說輸出I'M A COOL GOOD BOY
運(yùn)行環(huán)境vs2017