栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Const和指针

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Const和指针

这里写目录标题
  • Const和指针
    • Const在C和C++中的区别
    • Const与指针的关系
    • 常变量与指针
    • 同类型指针的赋值兼容规程

Const和指针 Const在C和C++中的区别
int main()
{
    const int n=0;//C语言以变量为主。
    int ar[n]={1,2};//error;
    int *p=(int*)&n;//
    *p=100;
    printf("%n=%d *p=%d n",n,*p);
    return 0;
}

int main()
{
    const int n=10;//C++语言中以常量为主。
    int  ar[n]={1,2,3,4};//ok;
    int *p=(int *)&n;//
    *p=100;
    cout<<"n="<int main()
{
    int a=0,b=10;
    int *p1=&a;      //普通指针
    const int *p2=&a;//指向为常性(解引用为常性)
    int const *p2=&a;

    int * const p3=&a;//指针变量自身为常性
    const int * const p4=&a; //指向(解引用)和指针变量自身都为常性
}

int main()
{
    int a=0;
    int *p1=&a;    //ok;
    const int *p2=&a;  //ok;
    int * const p3=&a;  //ok;
    const int * const p4=&a; //ok;
    return 0;
}
//编译方式不同
常变量与指针
int main()
{
    const int a=10;
    int *p1=&a;  //error;
    const int *p2=&a;  //ok;
    int * const p3=&a; //error;
    const int * const *p4=&a; //ok;
    int *p5=(int*)&a; //ok 不安全
    return 0;
}
同类型指针的赋值兼容规程
int main()
{
    int a=10,b=20;
    in *p=&a;
    int *s1=p;          //ok;
    const int *s2=p;    //ok;
    int * const s3=p;   //ok;
    const int * const s4=p; //ok;
}
总结:能力强的指针赋值为能力收缩的指针
练习1
int main()
{
    int a=10,b=20;
    in *p=&a;
    int *s1=p;          //ok;
    const int *s2=p;    //ok;
    int * const s3=p;   //ok;
    const int * const s4=p; //ok;
}
练习2
int main()
{
    int a=10,b=20;
    int * const 0=&a;
    int *s1=p;         //
    const int *s2=p;   //
    int * const s3=p;  //
    const int * const s4=p; //
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/879580.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号