【C++】const关键字小结(英文)

以后尝试着多用英文来写博客,最近看python-mysql的manual真的是不太舒服,18-10-4号刚出的,100页也没有翻译版本,只能硬着头皮看英文版本的

[C++] "Use const whenever u need"

1. variables

we got two types:

1.1 const int num
1.2 int const num
1.3 Usage

Their functions are the same

 

2. pointers

we got three types:           


2.1 const int* p_num            

the value of p_num is not changeable 

2.2 int* const p_num            

the direction of p_num is not changeable

2.3 const int * const p_num    

both the value and direction are not changeable

3. functions

3.1 declaration


the keyword - "this" in c++ has many features:

3.1.1 keyword -> "this"

for the normal member function which is not decorated with keyword 'const',keyword - 'this'
is a pointer(type:  class*  const) pointing to the object, while the class type with keyword - 'const' is a pointer (type:const class* const) pointing to a const object  

Eg:

Example 1:

class A {public: int func(int p){}};

It equals:

int func(A* const register this, int p); 

 

3.1.2 const char* & char*

you may not know the differences between const char* and char*,but it's the truth
that these two types of pointer will be regraded as different types of pointers
and one of them can not be assigned with the value of the other one unless you use the
casting methods(强制类型转换)

3.2 function definiton


If u wanna improve the speed of you program, one feasible idea is to use const with reference or pointer:
Like func(const classType* object) or func(const classType& object) will be much faster than func(classType object)cause the prevoius one will use the constructor and destructor which take time, but if you use keyword - const with reference or pointer, the data will be protected as no constructor or destructor will be used, which helps with saving a lot of time 


3.3 function return value


If u define a return value like const int* getResult(), then when u use this function,u can just use a variable like const int* num to fetch the return value of the function but for variable like int* getter, definitely not

3.4 function parameters

this has been declared in 2

[the differences between const in the front and const in the end]

4.  Summary

From the summary above,it's clear that when we use const in the front,we use it to control the
type of the return value, however when we use keyword - const at the end of the function decleration,
that means the type of function has been switched to a state that can only use the same type of the
functions and can not change any values of the class(maybe it's function is just for reading but not writting)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值