注:IDE vs2013
const定义常量
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
const int x = 3;
system("pause");
return 0;
}
此时的x为一个常量,不能再给x赋值,比如x=5;
就是错误的;
此时const相当于#define
。
const与指针
1
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int x = 3;
int y = 4;
const int *p = &y;
cout << *p << "," << x << "," << y << endl;
p = &x;
cout << *p << "," << x << "," << y << endl;
x = 5;
cout << *p << "," << x << "," << y << endl;
system("pause");
return 0;
}
const int *p = &y;
等价于int const *p = &y;
,此时定义*p
为一个常量,不能为其赋值,比如*p=10
;就是错误的,但是可以对p赋值,上述程序相当于将p的指向由y改向x,并且可以通过改变x来改变*p
。
如图:

2
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int x = 4;
int z = 5;
int *const q = &z;
cout << *q << "," << z << endl;
//q = &x; // 错误
*q = 10;
cout << *q << "," << z << endl;
z = 6;
cout << *q << "," << z << endl;
system("pause");
return 0;
}
将q定义为常量,不能对q赋值,即不能改变q的指向,但是可以对*q
赋值,同时也会改变z的值,z的改变也会改变*q
。

const与引用
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int x = 3;
int y = 4;
int const &z = x;
cout << z << ',' << x << endl;
//z = y; //错误
x = 5;
cout << z << "," << x << endl;
system("pause");
return 0;
}
不能再对z赋值,但是可以改变x从而对z进行改变。

指针与引用
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int x = 10;
int *p = &x;
cout << x << "," << *p << endl;
cout << &x << "," << p << endl;
system("pause");
return 0;
}
x *p
表示数字
&x p
表示地址
