zoukankan      html  css  js  c++  java
  • const

    #include "stdafx.h"
    #include <iostream>
    
    
    
    int main()
    {
        //an object can not to be modified
        char dat = 0;
        const char i = 9;
        
        const char *p = &i;    //data is const,pointer is not
        p++;
    
        char *const p1 = &dat; //pointer is a const, dat is not a const
        (*p1)++;
    
        char const *p2 = &dat;  //data and pointer are both const    
    
    
        const char* const p3 = &i;    //data and pointer are both const
    
        return 0;
    }
    • if const is on the left of *,data is const  //如果const在*左边数据就是const类型
    • if const is on the right of *,pointer is const
    • why use const
      • Guards anainst inadvertent write to the variable   //防止无意的改写数据
      • Self documenting                                                  //定义常量
      • Enables compiler to do more optimiztion, making code tighter   //使编译器做优化,使程序更加严谨
      • const means the variable can be put in the rom       //const变量意味着变量将被存到rom区域
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    // constant_member_function.cpp  
    class Date
    {
    public:
        Date(int mn);
        int getMonth()const;     // A read-only function  
        void setMonth(int mn);   // A write function; can't be const  
    private:
        int month;
    };
    
    Date::Date(int mn)
    {
        month = mn;
    }
    
    int Date::getMonth()const
    {
        return month;        // Doesn't modify anything  
    }
    void Date::setMonth(int mn)
    {
        month = mn;          // Modifies data member  
    }
    int main()
    {
        Date MyDate(7);
        const Date BirthDate(1);
        cout << BirthDate.getMonth() << endl;
        MyDate.setMonth(4);    // Okay  
        //BirthDate.setMonth(4); // C2662 Error  
        return 0;
    }
    • const 类对象   该对象只能读取数据,不能修改参数
    • const类函数    该函数只能返回数据,不能传入参数改变函数内数据。
  • 相关阅读:
    来电科技:基于Flink+Hologres的实时数仓演进之路
    实时计算 Flink 版总体介绍
    阿里云江岑:云原生在边缘形态下的升华
    xshell帮助
    版本控制工具之git
    批量修改ubuntu用户sudo免密码
    matplotlib按钮控制图像显示
    为ssh主机设置别名
    VScode正则表达式批量删除字符串
    SQL Server 操作XML数据
  • 原文地址:https://www.cnblogs.com/bixiaopengblog/p/8318932.html
Copyright © 2011-2022 走看看