const

来源:互联网 发布:知行结合爱国 编辑:程序博客网 时间:2024/05/22 03:20

const

const int a = 10;const int *a = &b; //*a不能被修改int const *p = &b; //*a不能被修改int *const p = &b; // a不能被修改const int * const p = &c; // both a and *a can not be modifiedextern const int var; //var的原型不一定是const,但在这里不能修改

Const member function usage

  • Repeat the const keyword in the defination as well as the declaration.
    • int get_day() const;
    • int get_day() const { return day; }
  • Function members that do not modify data should be declared const.
  • Const member functions are safe for const objects.

不可修改的对象

#include <iostream>using namespace std;class A {private:    int i;public:    A():i(10){}    void f(){cout << "f()" << endl;}//参数:A* this    void f() const {cout << "f() const" << endl;}//参数:const A* this};int main(int argc, char const *argv[]){    const A a;    A b;    a.f();    b.f();    return 0;   }

代码段的变量不可修改

#include <iostream>using namespace std;int main(int argc, char const *argv[]){    char *s = "hello world"; //Warning - conversion from string literal to 'char *' is deprecated,加上const可以去掉warning.    cout << s << endl;      printf("s's address : %p\n", s);    printf("main        : %p\n", main);    s[0] = 'B';    cout << s << endl;    return 0;}

Error: Bus error

Error是因为:”hello world”是存在代码段的,代码段是不可修改的。

0 0
原创粉丝点击