C++之const
来源:互联网 发布:m2m 物联网 java 技术 编辑:程序博客网 时间:2024/06/15 20:21
const设计的本质是为了保护成员不被修改,但是在生产环境下会遇见许多情形,如下:
#include<iostream>using namespace std;class data{ public: void get(){ cout<<"data::get()"<<endl; }};class test{ public: test(){ a=1; b=10; } void show(int i){ cout<<"show(int i)"<<endl; } //void show(const int i){//传值调用const不能实现调用,编译错误 // cout<<"show(const int i)"<<endl; //} void print(int &i){ cout<<"print(int &i)"<<endl; } void print(const int& i){//利用const参数完成重载 cout<<"print(const int& i)"<<endl; } void fun(){ cout<<"fun()"<<endl; } void fun() const{//利用const完成函数重载 cout<<"fun() const"<<endl; cout<<++a<<endl;//const函数能修改mutable变量,2 cout<<b<<endl;//const函数可以访问非const成员变量但不能修改,10 //++b;//const函数不能修改成员,编译错误 //show(1);//const函数不能调用非const成员,编译错误 } void nonConstFun(){ cout<<"nonConstFun()"<<endl; } void getdata() const{ //D.get();//const函数访问非const成员对象,编译错误 const_cast<data*>(&D)->get(); D2.get(); } public: mutable int a; int b; data D; mutable data D2;};int main(){ test one; const test two; int i=1; const int j=1; one.show(i);//对于非指针和非引用来说是传值调用故const不能重载,show(int i) one.show(j);//show(int i ) one.print(i);//非const的引用参数重载print(int &i),指针类似 one.print(j);//const引用参数的重载print(const int& i) one.fun();//非const对象优先调用非const成员函数 fun() two.fun();//const对象调用const成员函数fun() const //two.nonConstFun();//const对象调用非const成员,编译出错,const对象只能调用const成员函数,理由是防止成员函数篡改成员 two.getdata();//data::get() return 0;}
执行结果:show(int i)
show(int i)
print(int &i)
print(const int& i)
fun()
fun() const
2
10
data::get()
data::get()
总结:
const对象因为数据成员不能被修改所以只能调用const成员函数。
const成员函数成为“只读”函数所以只能调用const成员函数。某些特殊比如mutable和const_cast情形另当别论
对象. 成员函数
对象 成员函数 对/错
1、 const const 对
2、 const non-const 错
3、 non-const const 对
4、 not-const non-const 对
成员函数调用成员函数
成员函数 成员函数 对/错
5、 const const 对
6、 const non-const 错
7、 non-const const 对
8、 non-const non-const 对
一直没搞清楚volatile变量附上:volatile变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了。精确地说就是,优化器在用到这个变量时必须每次都小心地重新读取这个变量的值,而不是使用保存在寄存器里的备份。
#include<iostream>#include<unistd.h>#include<pthread.h>using namespace std;class test{ public: void show() const{ pthread_mutex_lock(&mutex); cout<<"pthread_mutex_lock"<<endl; pthread_mutex_unlock(&mutex); } test(){ pthread_mutex_init(&mutex,NULL); } private: //pthread_mutex_t mutex;//编译错误 mutable pthread_mutex_t mutex;//为了能让const成员函数能使用互斥量最好将互斥量都声明为mutable};int main(){ test one; one.show(); return 0;}
输出:
pthread_mutex_lock
- c/c++之const
- C语言之const
- C语言之const
- C-关键字之const
- C基础之CONST
- C语言修饰词之const
- C/C++之const关键字
- C/C++ Const之我见
- C语言总结之const
- C/C++关键字之const
- C语言关键字之const
- 《C关键字分析》之const
- c语言之const理解
- C语言之关键字const
- c语言基础之const
- C语言之关键字const
- C语言感悟之const
- 杂记之C语言之关键字const
- iocomp数码管控件
- 创业杂谈
- POJ 1330 LCA入门题(Tarjan)
- eclipse web工程导入到Tomcat
- 面试体验:Microsoft 篇
- C++之const
- JavaScript第6课-JS HTML DOM
- [智力题] 用信息熵解决天平跟毒药问题
- JAVA可重入锁ReentrantLock和synchronized关键字
- 多元huffman码变形
- MFC实现画图工具中的画线功能(一)
- 面试体验:Facebook 篇
- RAC维护工具集
- to_yminterval