1 #include <iostream>
2 #include <string>
3 #include <vector>
4
5
6 using namespace std;
7
8 int main()
9 {
10
11 string s("hello world!"); //定义一个字符串并初始化
12 string *sp=&s; //定义一个指针变量指向字符串地址
13 string* ps; //指针也可以这样定义
14 string* ps1,ps2l; //此时定义指针时ps1是指针变量 ps2是普通变量
15 cout<<s<<endl;
16 cout<<*sp<<endl;
17 //定义指针
18 vector<int> *pvec;
19 int *ip1,*ip2;
20 double *dp2;
21 //
22 int ival=1024;
23 int *pi=0; //指针是0 不指向任何对象
24 int *pi2=&ival;
25 pi=pi2;
26 //可以用一个常量初始化指针
27 const int a=0;
28 ip1=a;
29 //是万能指针 可以指向任何一种类型
30 void *pv;
31 //指针的指针
32 int x=1024;
33 int *op=&x;
34 int **op1=&op;
35 cout<<**op1<<endl;
36
37 //======================================================
38 //使用指针访问数组
39 const size_t arr_sz=5;
40 int a[arr_sz]={9,2,4,6,8};
41 int *p=a;//指针指向数组的第一个元素
42 cout<<*a<<endl;
43 cout<<*p<<endl;//输出
44 //解引用
45 int last=*(a+4);
46 cout<<last<<endl;
47
48 int *p1=a;
49 cout<<*p1<<endl;
50 //p[1]相当于指针的加法
51 int j=p1[1]; //p=&a[0] p[1]=p+1
52 cout<<j<<endl;
53 //==========================
54 //指针循环数组和迭代器循环向量比较
55 for(int *pbegin=a,*pend=a+arr_sz;pbegin!=pend;pbegin++)
56 {
57 cout<<*pbegin<<endl;
58 }
59 //===========================
60 vector<int> vec;
61 vec.push_back(1);
62 vec.push_back(2);
63 vec.push_back(3);
64 vec.push_back(4);
65 vec.push_back(5);
66 for(vector<int>::iterator iter=vec.begin();iter!=vec.end();iter++)
67 {
68 cout<<*iter<<endl;
69 }
70 //===============================================
71 double a=1.2;
72 double *p=&a;
73 //如果一个指针指向常对象 必须是一个常量指针
74 const double pi=3.14;
75 //p=&p1; 错
76 const double *cp;
77 cp=π
78 cp=&a; //可以指向非常对象的指针 但是不能修改值
79
80 //常指针;
81 int num=9;
82 int *const cur=# //常指针之前必须进行初始化 并且只能指向这一个变量
83 //指向常对象的常指针
84 const double *const pi_p=π
85 return 0;
86 }