zoukankan      html  css  js  c++  java
  • const

    一.const修饰成员变量

    1.const修饰类数据成员必须要初始化

    #include <iostream>
    using namespace std;
    class A
    {
    public:
       A()
       {
          cout << "const x = " << x << endl;
       }
    private:
       const int x;
    };
    
    int main()
    {
       A a;
       return 0;
    }

    上面代码没有对成员变量进行初始化,编译的时候会报如下错误

    /home/zzz/Workspace/test/cplusplus/const.cpp: In constructor ‘A::A()’:
    /home/zzz/Workspace/test/cplusplus/const.cpp:6:4: error: uninitialized const member in ‘const int’ [-fpermissive]
        A()
        ^
    /home/zzz/Workspace/test/cplusplus/const.cpp:11:14: note: ‘const int A::x’ should be initialized
        const int x;

    const成员初始化第一种在类内

    #include <iostream>
    using namespace std;
    class A
    {
    public:
       A()
       {
          cout << "const x = " << x << endl;
       }
    private:
       const int x = 100;
    };
    
    int main()
    {
       A a;
       return 0;
    }

    const成员初始化第二种在初始化列表

    #include <iostream>
    using namespace std;
    class A
    {
    public:
       A():x(100)
       {
          cout << "const x = " << x << endl;
       }
    private:
       const int x;
    };
    
    int main()
    {
       A a;
       return 0;
    }

    2.const修饰的数据成员可以在非const函数中使用,但不可以修改

     二.const修饰成员函数

    (const可以修饰类成员函数不可以修饰全局函数)

    const修饰函数以后承诺不改变,在本函数中不会发生,改变数据成员的行为

    只能调用const成员函数

    void foo()const
    {
    }

    const修饰函数可以构成重载  

    const构成的重载函数,非const对象,优先调用非const版本
    const对象只能调用const版本
    void foo() { } void foo()const { }


    void foo(int& a, int& b)
    {
    }
    void foo(const int& a, const int& b)
    {
    }

    三.const修饰对象

    const修饰对象,其内可以有非const数据成员,但不可修改。只能调用const成员函数

  • 相关阅读:
    ceph
    分布式网关层
    function declarations are hoisted and class declarations are not 变量提升
    js为Object对象动态添加属性和值 eval c.k c[k]
    方法就是一种变量
    static 不被实例调用
    WePY根据环境变量来改变运行时的参数
    函数类型实现接口——把函数作为接口来调用
    为什么需要onRoute函数?
    504 Gateway Timeout Error 502 Bad Gateway
  • 原文地址:https://www.cnblogs.com/aelite/p/10410113.html
Copyright © 2011-2022 走看看