//const与基本数据类型 //const与指针类型 #include <iostream> using namespace std; int main() { const int x = 10; //x = 20; 此处会报错!!!const修饰其值改变不了 return 0; } int main() { //1.const int *p = NULL; 与 int const *p = NULL等价 int x = 3, y = 4; const int *p = &x; p = &y; //此处正确 //*p = 4;此处为错误的 //2.int *const p = NULL; int *const p = &x; //p = &y; 此处报错 //3、const int * cont p = NULL; const int *const p = &x; //此处改变不了的 return 0; }
例子:
#include <iostream> using namespace std; int main() { const int x = 3; x = 5; int x = 3; const int y = x; y = 5; int x = 3; const int * y = &x; *y = 5; int x = 3, z = 4; int *const y = &x; y = &z; const int x = 3; const int &y = x; y = &z; return 0; }
结果如图:
具体请查看错误信息:
代码如下:
#include <iostream> using namespace std; int main() { const int x = 3; x = 5; return 0; }
结果:
#include <iostream> using namespace std; int main() { int x = 2; int y = 5; int const *p = &x; cout<<*p<<endl; p = &y; cout<<*p<<endl; return 0; }
#include <iostream> using namespace std; int main() { int x = 2; int y = 5; int const &z = x; z = 10; //会报错 x = 11; return 0; }
//函数使用const
//函数使用const #include <iostream> using namespace std; void fun(int &a, int &b) { a = 10; b = 22; } //函数有问题 //不能赋值 /* void fun1(const int &a, const int &b) { a = 33; b = 44; } */ int main() { int x = 2; int y = 5; fun(x, y); cout<<"函数没有const修饰的结果是: "<< x <<" , "<< y <<endl; /* int v = 3; int w = 4; fun1(v, w); cout<<"函数没有const修饰的结果是: "<<v<<" , "<<w<<endl; */ return 0; }
如果上例代码的注释去掉就会出现如下错误信息:
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-08 07:30:46