====指针运算==
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
int main()
{
int i[5]={1,2,3,4,5};
int *p=i;
cout<<*p<<endl;
p++;
cout<<*p<<endl;
p+=3; //注意不要越界
cout<<*p<<endl;
p-=2;
cout<<*p<<endl;
return 0;
};
======指针与常量限定符==
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
int main()
{
int k[2]={1,2};
const int *i=k;
i++;
cout<<*i<<endl;
*i=5; //error 指针常量不能改值
return 0;
};
=========
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
int main()
{
int k[2]={1,2};
int* const i=k;
//i++; //error const修饰的指针本身
cout<<*i<<endl;
*i=5;
cout<<*i<<endl;
return 0;
};
======指针与数组===
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
int main()
{
int k[4]={1,2,3,4};
cout<<*k<<endl;
int *p=k;
p++;
cout<<*p<<endl;
p=k+2; //p[2]={3,4} p看成数组
cout<<p[1]<<endl;
int i=9;
p=&i; //p[0]=9 p=9
cout<<p[0]<<endl;
return 0;
};
=====引用===
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
int main()
{
int i=6;
int& r=i; //i,r,指向同一空间,r为i的别名或引用
cout<<i<<endl;
cout<<r<<endl;
i++;
cout<<i<<endl;
cout<<r<<endl;
r++;
cout<<i<<endl;
cout<<r<<endl;
return 0;
};
======变量引用传递不同指针或引用区别==
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
//传值
void fun1(int i)
{
i++;
cout<<i<<endl;
}
//传引用
void fun2(int& i)
{
i++;
cout<<i<<endl;
}
//传指针
void fun3(int* i)
{
if(i)
{
(*i)++;
cout<<i<<endl;
}
}
int main()
{
fun1(5);
//fun2(5); //错误,文字常量不能作为引用
int i=8;
fun1(i);
cout<<i<<endl;
fun2(i);
cout<<i<<endl;
fun3(&i);
cout<<i<<endl;
return 0;
};
=========new/delete操作符===
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
int a=0; //全局存储空间
int main()
{
int b; //栈上空间
int *c=new int(0); //堆上空间
cout<<*c<<endl;
delete c;
return 0;
};
=======new操作符的两种用法===
//堆上为单独数据类型分配空间、创建单个变量,返回指向创建数据对象的指针
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
struct st
{
int a;
char b;
};
int main()
{
st* pst=new st();
delete pst;
return 0;
};
====
//创建数组连续空间,返回数组首地址。
#i nclude "stdafx.h"
#i nclude "iostream"
#i nclude "string"
using namespace std;
struct st
{
int a;
char b;
};
int main()
{
st* pst=new st[10];
delete [] pst;
return 0;
};