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类函数    该函数只能返回数据,不能传入参数改变函数内数据。
  • 相关阅读:
    Java.io.outputstream.PrintStream:打印流
    Codeforces 732F. Tourist Reform (Tarjan缩点)
    退役了
    POJ 3281 Dining (最大流)
    Light oj 1233
    Light oj 1125
    HDU 5521 Meeting (最短路)
    Light oj 1095
    Light oj 1044
    HDU 3549 Flow Problem (dinic模版 && isap模版)
  • 原文地址:https://www.cnblogs.com/bixiaopengblog/p/8318932.html
Copyright © 2011-2022 走看看