• C++ 关键字 const


    9. Const

    • declares a variable to have a constant value
    • Constants are variables
      • Observe(遵守) scoping rules
      • Declared with "const" type modifier

    9.1 Compile time constants

    • 编译时刻,可以确定值
      • value must be initialized
      • unless you make an explicit extern declaration;
    const int bufsize = 1024;
    
    // extern 声明
    extern const int bufsize;
    

    9.2 Run-time constants

    const int class_size = 12;
    int finalGrade[class_size];  // ok
    
    int x;
    cin >> x;
    const int size = x;
    double classAverage[size];   // error
    

    9.3 Pointers and const

    char* const q = "abc";  // q is const
    *q = 'c';   // OK
    q++;        // ERROR
    
    
    const char *p = "ABCD";  // (*p) is a const char
    *p = 'b';  // ERROR
    
    
    Person p1("Fred", 200);
    const Person* p = &p1;
    Person const* p = &p1;
    Person *const p = &p1;
    
    // const 位于星号前面,对象是 const
    // const 位于星号后面,指针是 const
    

    9.4 示例

    • a.cpp
    #include <iostream>
    using namespace std;
    
    int main()
    {
        //char *s = "hello world";
        // "hello world": 位于代码段, 代码段的内容,不能写
    
        char s[] = "hello world";
        // "hello world": 位于栈中
    
        cout << s << endl;
    
        s[0] = 'B';
    
        cout << s << endl;
    
        return 0;
    }
    

    9.5 const 函数

    • Repeat the const keyword in the definition as well as the declaration
    • Function members that do not modify data should be declared const.
    • const memeber functions are safe for const objects.
    int Date::set_day(int d) {
        day = d;
    }
    
    int Date::get_day() const {
        day++;      // ERROR modifies data member
        
        set_day(12);    // ERROR calls non-const member
    
        return day;     // ok
    }
    

    9.6 类中的 const

    • main.cpp
    #include <iostream>
    using namespace std;
    
    class A {
        int i;
    public:
        A() : i(0) {}
        void f() { cout << "f()" << endl; }
        void f() const { cout << "f() const" << endl; }
    };
    
    int main()
    {
        const A a;
        a.f();
    
        return 0;
    }
    
    // 解释:
    // void f()        实际为: void f(A* this)
    // void f() const  实际为: void f(const A* this)
    
    • 运行结果

    参考链接:

  • 相关阅读:
    2016.6.23 随笔———— AJAX
    2016.6.13 随笔————图像获取、处理,视频获取,png图片尺寸缩小
    2016.5.15 随笔————网页平面设计软件 Illustrator(Ai) 和 Photoshop(Ps) 简介
    学习的目的:理解<转>
    几点要求自己也可以借鉴
    手表电池
    许小年:宁可踏空,不可断粮<转>
    【微言大义】时间都去哪了?
    互联网趋势其实很浮夸
    解决Mac下GDB提示签名错误
  • 原文地址:https://www.cnblogs.com/linkworld/p/16370145.html
Copyright © 2020-2023  润新知