指针

来源:互联网 发布:office画图软件 visio 编辑:程序博客网 时间:2024/06/06 01:41

赋给指针0值时,这个0值必须是在编译时可获得的0值,例如数值0,或const常量0值,就像定义数组长度时,需要用enum常量或const常量相同。


预处理变量NULL定义在cstdlib头文件中,其值为0。在代码中使用该值,则编译时会自动被数值0替换。

对为NULL值的指针变量解引用,则会出现运行错误。

#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
    int *point=NULL;
    cout<<*point;
    return 0;
}

上述程序编译通过,运行出错。


指针和引用的区别:(1)不论是const引用还是非const引用,都必须进行初始化;(2)不论是const引用还是非const引用,都只能始终绑定同一个变量,不能改变。


不能使用void *指针保存const对象的地址,必须使用const void*类型的指针保存const对象的地址。

#include <iostream>
#include <cstdlib>
using namespace std;
int main(void)
{
    const int a=100;
    const int *pointa=&a;
    double b=3.2;
    double *pointb=&b;
    void *vob=&b;
    pointb=(double*)vob;
    cout<<(int)b<<endl<<*((int*)vob)<<endl<<*((int*)pointb)<<endl<<*((double *)vob);
    return 0;
}

double*转化为int*是把double指针所指的空间解释成int类型,同double转化为int不同。


指针所知的对象的值能否修改完全取决于该对象的类型,而不是指针的类型,或是指针自以为所指向的数据类型。

#include <iostream>
using namespace std;
int main(void)
{
    int b=20;
    const int *cpb=&b;
    b=30;
    cout<<*cpb<<endl;
    int *pb=&b;
    *pb=40;
    cout<<*cpb<<endl;
    const int cb=b;
    cout<<cb;
    return 0;
}

上述程序中,虽然*cpb定义为指向const对象的指针,但是实际指向的非const类型的变量,因此,即使*cpb无法改变变量b的值,但是b自己可以改变,所以程序运行结果如下:



使用typedef隐藏符合类型,要注意正确理解定义的变量,例如:

typedef string *pstring;

const pstring cstr;

此时,定义的cstr相当于string *const cstr;cstr本身是const类型的。

原创粉丝点击