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;
}
#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;
}
#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的地址,也就是说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;
}
代码
这样都可以,说明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;
cout << a <<endl;
int e =5;
a = &e;
cout << a <<endl;
cout << *a<< endl;
}
(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;
}
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;
}
const int * const a对于这种写法,a和*a都是常量,都不能被改变!