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