C++ const总结
2016-06-16 09:05
337 查看
先说结论
非引用类型的赋值无所谓const。
const引用可以指向const及非const。但非const引用只能指向非const。
指向const的指针,可以指向非const。但指向非const的指针,只能指向非const。
注意:上面说的都是变量赋值!
对于函数来说同理,
非const引用的形参只能接收非const引用的实参;const引用的形参可以接收任意引用的实参。
非const指针的形参只能接收非const指针的实参;const指针的形参可以接收任意指针的实参。
对引用来说,const形参和非const形参,函数是不同的!!!指针没这区别。
插一句
代码说明一切
函数测试代码
非引用类型的赋值无所谓const。
const引用可以指向const及非const。但非const引用只能指向非const。
指向const的指针,可以指向非const。但指向非const的指针,只能指向非const。
注意:上面说的都是变量赋值!
对于函数来说同理,
非const引用的形参只能接收非const引用的实参;const引用的形参可以接收任意引用的实参。
非const指针的形参只能接收非const指针的实参;const指针的形参可以接收任意指针的实参。
对引用来说,const形参和非const形参,函数是不同的!!!指针没这区别。
插一句
指针和引用,非const的不能指向const吧,为什么char *cc="abbc"就可以? 网上说“是字面值常量的指针其实指向临时对象,C++规定指向临时对象的指针必须const”。 那这里C++是怎么处理的? this is not good wording... it starts from "temporary objects can be bound to const references and have their lifetimes extended to that of the bound reference", and you can only get a pointer-to-const from such a ref but this is constraint is [b]relaxed[/b] in C++11, with the addition of rvalue references
代码说明一切
#include <iostream> #include <string> using namespace std; //test const int main(){ //------------测试非引用------------ int no=10; const int no2=no; //OK int no3=no2; //OK! //上面得出结论:非引用类型的赋值无所谓const //------------测试引用------------ int &noref=no; const int &noref1=no; // int &no2ref=no2; const int &no2ref1=no2; int &no3ref=no3; const int &no3ref1=no3; // 上面得出结论:const引用可以指向const及非const。但非const引用只能指向非const。 //------------测试指针------------ int *pno=&no; const int *pno_1=&no;//指向const的指针,可以指向非const // int *pno2=&no2;//指向非const的指针,只能指向非const const int *pno2_1=&no2; int *pno3=&no3; const int *pno3_1=&no3; // 上面得出结论:见备注 return 0; }
函数测试代码
#include <iostream> using namespace std; void print(int&); void print2(const int& val); void getx(char *c); void getx2(const char *c); int main(){ int v1=2; const int v2=10; print(v1); // print(v2);//[Error] invalid initialization of reference of type 'int&' from expression of type 'const int' print2(v1); print2(v2); int& v3=v1; const int& v4=v2; print(v3); // print(v4);////[Error] invalid initialization of reference of type 'int&' from expression of type 'const int' print2(v3); print2(v4); //总结,非const的引用类型的形参,只能接收同类型的实参! // ------------------------ char *c1="abc"; const char *c2="xyz"; getx(c1); // getx(c2);//[Error] invalid conversion from 'const char*' to 'char*' [-fpermissive] getx2(c1); getx2(c2); return 0; } void print(int& val){ cout << val << endl; } void print2(const int& val){ cout<<val<<endl; } void getx(char *c){ cout<<c<<endl; } void getx2(const char *c){ cout<<c<<endl; }
相关文章推荐
- 小玩文件3
- 哈夫曼算法(haffman)实现压缩和解压缩-C语言实现
- MFC多线程的创建
- Qt/C++ qss一些记录
- 第9周课后实践1-①
- C++关于指针----参考图
- 求最大公约数
- C++中cin、cin.get()、cin.getline()、getline()、gets()等函数的用法
- c语言中strtok的使用
- C++中map操作
- *leetcode #99 in cpp
- 「C语言」Windows+EclipseCDT下的C语言开发环境准备
- C++学习写在前面
- Eclipse运行C++问题Launch failed,Binary not found
- c++ 中__declspec 的用法
- Reconstruct Itinerary
- python调用c/c++
- C++第二次作业(补)
- mac 上编译 运行cpp 文件(c++)
- 多参数函数