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类函数    该函数只能返回数据,不能传入参数改变函数内数据。
  • 相关阅读:
    4.9cf自训9..
    数位dp-入门模板题 hdu2089
    熟能生巧 汽车停车入位技巧解析-倒车入库--侧边停车
    MyBatis参数传入集合之foreach动态sql
    jquery如何判断checkbox(复选框)是否被选中
    Mybatis关联查询(嵌套查询)
    Mysql 分页语句Limit用法
    $.ajax返回的JSON格式的数据后无法执行success的解决方法
    JavaWeb学习总结(十二)——Session
    Spring MVC中Session的正确用法之我见
  • 原文地址:https://www.cnblogs.com/bixiaopengblog/p/8318932.html
Copyright © 2011-2022 走看看