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; //&紧随类名出现,因此是申明的一部分,r是一个引用
int *p; //*紧随类型名出现,因此是申明的一部分,p是一个指针
p = &ival; //&出现在表达式中,是一个取地址符
*p = ival; // *出现在表达式中,是一个解引用符
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;
}
// 不知道在定义的时候加&或者*和定义完成后重新赋值的时候加&或者*有什么区别呢?
下面是引用和指针的问题:
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
*/
网友评论