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类函数    该函数只能返回数据,不能传入参数改变函数内数据。
  • 相关阅读:
    IIS 和 各个协议
    Hibernate 框架基本知识
    各类主流框架及设计模式简介
    PHP微信公众开发笔记(七)
    PHP微信公众开发笔记(六)
    《Programming in Lua 3》读书笔记(二十七)
    《Programming in Lua 3》读书笔记(二十八)
    《Programming in Lua 3》读书笔记(二十六)
    PHP微信公众开发笔记(五)
    PHP微信公众开发笔记(四)
  • 原文地址:https://www.cnblogs.com/bixiaopengblog/p/8318932.html
Copyright © 2011-2022 走看看