学习1.2

const 符号常量;
(1)const int *a
(2)int const *a
(3)int * const a
说明上面三种描述的区别;

测试原代码:

#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int b = 2;
const int *a = &b;
const int c = 3;
int d = 4;
}
(1)针对第一种情况:

#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int b = 2;
const int *a = &b;
const int c = 3;
int d = 4;
*a = d;
}
 error C3892: “a”: 不能给常量赋值

#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int b = 2;
const int *a = &b;
const int c = 3;
int d = 4;
a
= &d;
}
运行正确:a = 4(d的值)

因此对于这种情况来说可以改变a的地址,也就是说a是个变量;但是不能*a却是个常量,不能直接改变*a的值。

(2)

#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int b = 2;
int const *a = &b;
const int c = 3;
int d = 4;
*a = d;
cout
<< *a<< endl;
}
error C3892: “a”: 不能给常量赋值
代码
#include<iostream>
using namespace std;
int main()
{
int b = 2;
int const *a = &b;
cout
<< a <<endl;
const int c = 3;
int d = 4;
a
= &d;
cout
<< a <<endl;
int e =5;
a
= &e;
cout
<< a <<endl;
cout
<< *a<< endl;
}
这样都可以,说明a也是个变量,只有*a是个常量。

(3)

#include<iostream>
using namespace std;
int main()
{
int b = 2;
int * const a = &b;
cout
<< a <<endl;
const int c = 3;
int d = 4;
a
= &d;
}
error C3892: “a”: 不能给常量赋值

a是个常量,不能被赋值。

#include<iostream>
using namespace std;
int main()
{
int b = 2;
int * const a = &b;
cout
<< a <<endl;
const int c = 3;
int d = 4;
*a = d;
}

 

ok,*a是个变量

const int * const a对于这种写法,a和*a都是常量,都不能被改变!

posted @ 2010-12-23 15:33  hailong  阅读(221)  评论(0编辑  收藏  举报