void main()
{
int ival = 42;
int *p = &ival;
cout << "p: "<< p<<"\n"
<< "*p: "<<*p;
}
// p:0015FE28 訪問變量ival的地址郭卫,或者說p是指向變量ival的指針
// *p:42 *為解引用符稍坯,訪問ival的對象
void main()
{
int ival = 42;
int *p = &ival;
*p = 0;
cout << "p: " << p << "\n"
<< "*p: " << *p<<"\n"
<<"ival: "<<ival;
}
// p:0028FEE0 訪問變量ival的地址锌畸,或者說p是指向變量ival的指針
// *p:0 *為解引用符姐扮,訪問ival的對象
// ival:0
void main()
{
int ival = 42;
int &r = ival; //&緊隨類名出現(xiàn),因此是申明的一部分剖煌,r是一個引用
int *p; //*緊隨類型名出現(xiàn)罗丰,因此是申明的一部分蔗喂,p是一個指針
p = &ival; //&出現(xiàn)在表達式中,是一個取地址符
*p = ival; // *出現(xiàn)在表達式中备恤,是一個解引用符
int &r2 = *p; //&是申明的一部分稿饰,*是一個解引用符
cout << "p: " << p << "\n"
<< "*p: " << *p << "\n"
<< "ival: " << ival <<"\n"
<< "&ival: " << &ival << "\n"
<< "&r: " << &r << "\n"
<< "&r2: " << &r2;
}
p: 002AFE88
*p: 42
ival: 42
&ival: 002AFE88
&r: 002AFE88
&r2: 002AFE88
void main()
{
int ival = 42;
int r = ival;
int *p = &ival;
cout << "p: " << p << "\n"
<< "*p: " << *p << "\n"
<< "ival: " << ival <<"\n"
<< "&ival: " << &ival << "\n"
<< "&r: " << &r << "\n"
<< "r: " << r;
}
// 不知道在定義的時候加&或者*和定義完成后重新賦值的時候加&或者*有什么區(qū)別呢?
下面是引用和指針的問題:
void main()
{
int ival = 42;
int &t = ival; // t為引用露泊,在修改了t=0之后喉镰,p也進行了修改
int *p;
p = &t;
cout << "p: " << p << "\n" << "*p: " << *p << endl;
cout << "ival: " << ival << "\n" << "&ival: " << &ival << endl;
t = 0;
//*p = 0;
cout << "p: " << p << "\n" << "*p: " << *p << endl;
cout << "ival: " << ival << "\n" << "&ival: " << &ival << endl;
}
/*
p: 0028F93C
*p: 42
ival: 42
&ival: 0028F93C
p: 0028F93C
*p: 0
ival: 0
&ival: 0028F93C
*/
void main()
{
int ival = 42;
int *t = &ival; // t為指針指向ival的地址,在t修改了后惭笑,p的指針仍指向ival的地址
int *p;
p = t;
cout << "p: " << p << "\n" << "*p: " << *p << endl;
cout << "ival: " << ival << "\n" << "&ival: " << &ival << endl;
t = 0;
//*p = 0;
cout << "p: " << p << "\n" << "*p: " << *p << endl;
cout << "ival: " << ival << "\n" << "&ival: " << &ival << endl;
}
/*
p: 0037FBAC
*p: 42
ival: 42
&ival: 0037FBAC
p: 0037FBAC
*p: 42
ival: 42
&ival: 0037FBAC
*/