C++ 常函数
常函数的意义对与普通函数来说,因为const关键字的增加,体现在对类成员的保护上,现在加以讲解:
#include<iostream>usingnamespacestd;classCtest{private:inta;public:Ctest(inta=2){this->a=a;}intdoubleA()const{returna*2;}};intmain(){Ctest*cts=newCtest(2);cout<<cts->doubleA()<<endl;deletects;return0;}
结果:
常函数->
int doubleA() const 就是在函数后加const
需要注意的是 :
①:构造函数和析构函数不可以是常函数
②:常函数不能对class的类成员进行修改(只能调用)如下面是不可以的:
但是可以对本函数内部声明的参数进行修改
③:常函数的this指针,有别于普通函数的this指针
#include<iostream>usingnamespacestd;classCtest{private:inta;public:Ctest(inta=2){this->a=a;}intdoubleA()const{returna*2;}constCtest*my()const{returnthis;}Ctest*my1(){returnthis;}};intmain(){/*Ctest*cts=newCtest(2);cout<<cts->doubleA()<<endl;deletects;*/Ctestcts(3);cout<<cts.my()->doubleA()<<endl;return0;}
这里有个注意点:常对象只能调用常对象,如下面是不允许的:
另外 :
#include<iostream>usingnamespacestd;classCtest{private:inta;public:Ctest(inta=2){this->a=a;}intdoubleB(){returna*2;}intdoubleA()const{returna*2;}constCtest*my()const{returnthis;}Ctest*my1(){returnthis;}};intmain(){/*Ctest*cts=newCtest(2);cout<<cts->doubleA()<<endl;deletects;*/constCtestcts(3);cout<<cts.doubleA()<<endl;return0;}
用 const Ctest cts(3) 也是定义常对象
当然,下面的方案也行:
constCtest*cts=newCtest(3);cout<<cts->doubleA()<<endl;
总结 ,常函数具有保护类成员的作用。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。