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类函数    该函数只能返回数据,不能传入参数改变函数内数据。
posted @ 2018-01-19 21:38  peng_blog  阅读(163)  评论(0编辑  收藏  举报