代码改变世界

c++ primer学习笔记(8)-指针

2011-02-24 21:30  Clingingboy  阅读(420)  评论(0编辑  收藏  举报

理解这一点非常之关键

看例子.

string s("hello world");
string *sp = &s; // sp holds the address of s
  1. 首先定义了一个s的字符串
  2. 从第2行开始从右往左看.
  3. &表示取地址操作符
  4. *表明变量是一个指针变量
  5. 指针用于保存一个对象的地址

牢记以上几点

指针的定义和初始化

1.用*符号标识变量

vector<int>   *pvec;      // pvec can point to a vector<int>
int           *ip1, *ip2; // ip1 and ip2 can point to an int
string        *pstring;   // pstring can point to a string
double        *dp;        // dp can point to a double

2.声明风格

(1)

int *ip1, *ip2; // ip1 and ip2 can point to an int

(2)

double dp, *dp2; // dp2 is a ponter, dp is an object: both type double

(3)

string* ps; // legal but can be misleading


(4)

string* ps1, ps2; // ps1 is a pointer to string,  ps2 is a string

(5)

string* ps1, *ps2; // both ps1 and ps2 are pointers to string

风格的选择,不要让这么多声明方式混淆了你的思想,你可以选择你喜欢的方式

3.指针状态

  1. 保存对象地址
  2. 指向某个对象后面的另一对象
  3. 0值

指针赋值

看下面代码

int ival;
int zero = 0;
const int c_ival = 0;
int *pi = zero; // error: pi initialized from int value of ival
pi = zero;      // error: pi assigned int value of zero
pi = c_ival;    // ok: c_ival is a const with compile-time value of 0
pi = 0;         // ok: directly initialize to literal constant 0

1.不可以直接赋变量,即使值(非const状态下)为0
2.可以直接赋0或者const为0的变量

指针初始化或赋值必须为同类型

double dval;
double *pd = &dval;   // ok: initializer is address of a double
double *pd2 = pd;     // ok: initializer is a pointer to double

int *pi = pd;   // error: types of pi and pd differ
pi = &dval;     // error: attempt to assign address of a double to int *

void*指针

可保存任意类型对象的地址

double obj = 3.14;
double *pd = &obj;
// ok: void* can hold the address value of any data pointer type
void *pv = &obj;       // obj can be an object of any type
pv = pd;               // pd can be a pointer to any type