The meaning of the constant function is the same as the normal function, because the increment of the Const keyword is embodied in the protection of the class members, and is now explained: 650) this.width=650; "alt=" J_0003.gif "src=" http://img.baidu.com/ Hi/jx2/j_0003.gif "/>
#include <iostream>using namespace Std;class ctest{private:int a;public:ctest (int a = 2) {T His->a = A; } int Doublea () const {return a*2; }};int Main () {CTest * cts = new CTest (2); cout << Cts->doublea () << Endl; Delete cts; return 0;}
Results:
650) this.width=650; "title=" 01.png "alt=" wkiol1ko2tnacsi6aaaywcyhpa4138.png-wh_50 "src=" https://s2.51cto.com/ Wyfs02/m00/94/d6/wkiol1ko2tnacsi6aaaywcyhpa4138.png-wh_500x0-wm_3-wmp_4-s_4220892240.png "/>
Constant functions,
an int Doublea () const is the addition of a const after a function
It is important to note that:
①: Constructors and destructors cannot be regular functions
②: The constant function cannot modify class members (only calls) as follows:
650) this.width=650; "title=" 02.png "alt=" wkiol1ko2qjcb_qkaacbysvchd8725.png-wh_50 "src=" https://s5.51cto.com/ Wyfs02/m02/94/d6/wkiol1ko2qjcb_qkaacbysvchd8725.png-wh_500x0-wm_3-wmp_4-s_496505959.png "/>
However, you can modify the parameters declared inside this function
③: this pointer of the constant function, different from the this pointer of the normal function
#include <iostream>using namespace std;class Ctest{private: int a;public: ctest (&NBSP;INT&NBSP;A&NBSP;&NBSP;=&NBSP;2) { this->a = a; } int doublea () const { return a*2; } const ctest* my () const { Return this; } ctest* my1 () { return this; }};int main () { /*ctest * cts = new ctest (2); cout << cts->dOublea () << endl; delete cts;*/ Ctest CTS (3); cout << cts.my ()->doublea () << endl; return 0;}
Here's a note: A constant object can only invoke a constant object, as the following is not allowed :
650) this.width=650; "title=" 03.png "alt=" wkiol1ko3u-xvzxuaadikoxs2hq680.png-wh_50 "src=" https://s3.51cto.com/ Wyfs02/m01/94/d6/wkiol1ko3u-xvzxuaadikoxs2hq680.png-wh_500x0-wm_3-wmp_4-s_3702970445.png "/>
Other than that:
#include <iostream>using namespace std;class Ctest{private: int a;public: ctest (&NBSP;INT&NBSP;A&NBSP;&NBSP;=&NBSP;2) { this->a = a; } int doubleb () { return a*2; } int doublea () const { return a*2; } const ctest* my () const { return this; } ctest* my1 () { return this; &nbsP; }};int main () { /*ctest * cts = new ctest (2); cout << cts->doublea () << endl; delete cts;*/ const ctest cts (3); cout << cts.doublea () << endl; return 0;}
Using the const CTest CTS (3) is also a defined constant object
Of course, the following scenarios are also OK:
Const CTEST * cts = new CTest (3); cout << Cts->doublea () << Endl;
In summary, the constant function has the function of protecting class members.
This article is from the "Better_power_wisdom" blog, make sure to keep this source http://aonaufly.blog.51cto.com/3554853/1922882
C + + constant function long function