美文网首页
C++中的const

C++中的const

作者: caoxian | 来源:发表于2018-04-01 13:07 被阅读0次

    1.const 修饰常量:

    const修饰的变量不可变,只能在初始化时赋值。以下两种写法效果是一样的:

    const int a = 10;

    int const a = 10;


    2.修饰指针

    const在*左侧:修饰指针指向的变量为常量

    int a = 10;

    const int* p =  &a;

    int const* p =  &a;

    const在*右侧:修饰指针的值不能变,即指针本身为常量

    int* const p = &a;


    3.修饰引用

    不能通过引用修改变量的值

    int a = 10;

    const int& b = a;

    int& const b = a;        //修改b将无法修改a的值


    3. 修饰类成员变量

    用const修饰的类成员变量,只能在类的构造函数初始化列表中赋值,不能在类构造函数体内赋值。

    class A

    {public:

        A(int x) : a(x) // 正确  {

            //a = x;    // 错误

        }

    private:

        const int a;

    };


    4.修饰类成员函数

    用const修饰的类成员函数,在该函数体内不能改变该类对象的任何成员变量, 也不能调用类中任何非const成员函数。

    class A

    {public:

        int& getValue() const{

            // a = 10;    // 错误

            return a;

        }

    private:

        int a;// 非const成员变量

    };


    5.修饰类对象

    用const修饰的类对象,该对象内的任何成员变量都不能被修改。

    只能调用对象的const成员函数,不能调用非const成员函数。

    class A

    {

    public:

        void funcA() {}

        void funcB() const {}

    };

    int main

    {

        const A a;

        a.funcB();    // 可以

        a.funcA();// 错误

        constA* b =new A();

        b->funcB();// 可以

        b->funcA();// 错误

    }

    相关文章

      网友评论

          本文标题:C++中的const

          本文链接:https://www.haomeiwen.com/subject/nyhglttx.html