const

const

const int bufsize=1024

  • 必须初始化

external const int bufsize;

  • 本文件使用了一个外部的变量,不能修改,但是与bufsize本身是否能被修改无关
  • 编译器保证const

Pointters and const

  • 指针不能指向别人
  • 指向不能修改的变量

const指的是通过变量能不能修改而不是内存本身是不是const

  • const * const用前后区别
  1 #include<iostream>
  2 using namespace std ;
  3
  4 int main()
  5 {
  6     char * s="Hello World";  //code
  7     cout<<s<<endl;
  8     s[0]='B';
  9     cout<<s<<endl;
 10     return 0;
 11 }
~

const.cpp: In function ‘int main()’:
const.cpp:6:11: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
char * s=“Hello World”;

  1 #include<iostream>
  2 using namespace std ;
  3
  4 int main()
  5 {
  6     char s[]="Hello World";  //堆栈
  7     cout<<s<<endl;
  8     s[0]='B';
  9     cout<<s<<endl;
 10     return 0;
 11 }
~

object

  • int get_day() const
  • this 是 const
  • 函数没有修改成员变量
  1 #include<iostream>
  2 using namespace std;
  3 class A
  4 {
  5         int i;
  6 public:
  7         A():i(0){}
  8         void f(){cout<< "f()"<<endl;}
  9         void f() const {cout<<"const"<<endl;}  //隐形this
 10 };
 11 int main()
 12 {
 13     const A a;  //
 14     a.f();
 15     return 0;
 16 }
~
//result:
const
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值