const关键字

    xiaoxiao2021-03-25  91

    1.const修饰变量

    const代替#defineconst有类型,#define无类型,const节省空间,避免不必要的内存分配。

    const定义的常量在程序运行的过程中,只有一份拷贝,#define 定义的常量在内存中有若干个拷贝。编译器一般不会为const常量分配内存,而是将它们保存在符号表中,这使得它成为一个在编译期间的常量。

    Int a=100;

    Const int c=300;//修饰c为只读

    Const int* p1=&a;//const 修饰int* a的值不可以改变;

    Int * const p1=&a;//const 修饰p1,p1的值不可以更改;

    Int const* p1=&a;//const修饰*p1,a的值不可以改变。

    当对const修饰的变量取地址时,编译器会为变量分配内存。

    int main()

    {

    const int b = 5;

    int *p = NULL;

    p =const_cast<int*> (&b);

    *p = 555;

    cout << *p << endl;//输出555

    cout << b << endl;//输出b

    system("pause");

    return 0;

    }

    2.const修饰函数形参

    void fun(cosnt int a);//告诉编译器,a在函数体内不可以修改。

    3.const修饰类成员函数,使得成员函数成为常函数

    class A

    {

    public

    int fun()cosnt//调用函数fun时不能修改类中的数据。

    {

    }

    }

    4.const修饰函数的返回值

    const int *funconst int a

    {

    return &a;

    }

    转载请注明原文地址: https://ju.6miu.com/read-24971.html

    最新回复(0)